參考文章http://blog.guowenfh.com/2018/06/04/2018/learning-Promise/
promise對(duì)象用于表示一個(gè)異步操作的最終狀態(tài),以及返回的值
鏈?zhǔn)交卣{(diào),不用再寫callback
request(1)
.then(data=>{
console.log('promise',data)
return request(2)
})
.then(data=>{
console.log('promise',data)
return request(3)
})
.then(data=>{
console.log('promise',data)
})
.catch(data=>{
console.log('error')
})
function request(e){
return new Promise((resolve,reject)=>{
setTimeout(()=>{
switch (e) {
case 1:
resolve('success1');
break;
case 2:
resolve('success2');
break;
case 3:
reject('success3');
break;
default:
break;
}
},1000)
})
}
//promise success1
//promise success2
//error
Promise對(duì)象上的方法
Promise.all()會(huì)將多個(gè) Promise 實(shí)例封裝成一個(gè)新的 Promise 實(shí)例汹桦,新的 promise 的狀態(tài)取決于多個(gè) Promise 實(shí)例的狀態(tài)蚪燕,只有在全體 Promise 都為 fulfilled 的情況下咨跌,新的實(shí)例才會(huì)變成 fulfilled 狀態(tài)熊昌。喜滨;如果參數(shù)中 Promise 有一個(gè)失斔痢(rejected),此實(shí)例回調(diào)失敗(rejecte)狞膘,失敗原因的是第一個(gè)失敗 Promise 的結(jié)果。
fetch('https://cnodejs.org/api/v1/topics?tab=good&limit=10')
.then(res=>res.json())
.then(res=>{
const fecthList = res.data.map(t=>{
return fetch(`https://cnodejs.org/api/v1/topic/${t.id}`)
.then(res=>res.json())
// .then(res=>res.data) //return res.data
})
Promise.all(fecthList).then(list=>{ //返回一個(gè)數(shù)組
console.log(list)
})
})
Promise.race Promise.race 也會(huì)將多個(gè) Promise 實(shí)例封裝成一個(gè)新的Promise實(shí)例什乙,只不過(guò)新的 Promise 的狀態(tài)取決于最先改變狀態(tài)的 Promise 實(shí)例的狀態(tài)挽封。
fetch api模擬請(qǐng)求超時(shí)
Promise.race([
fetch('https://cnodejs.org/api/v1/topics?tab=good&limit=10'),
new Promise((resolve,reject)=>{
setTimeout(reject,1000,'error')
})
]).then(result=>{
console.log('then',result)
}).catch(error=>{
console.log('catch',error)
})
關(guān)于執(zhí)行順序
//在使用 Promise 構(gòu)造函數(shù)構(gòu)造 一個(gè) Promise 時(shí),回調(diào)函數(shù)中的內(nèi)容就會(huì)立即執(zhí)行臣镣,而 Promise.then 中的函數(shù)是異步執(zhí)行的场仲。
new Promise((resolve,reject)=>{
console.log('step 1')
resolve()
console.log('step 2')
}).then(()=>{
console.log('step 3')
})
console.log('step 4')
//step 1
//step 2
//step 4
//step 3
關(guān)于異步請(qǐng)求
一般可以使用異步請(qǐng)求來(lái)實(shí)現(xiàn)等待接口返回后函數(shù)再返回參數(shù)
const fetch = require('node-fetch')
async function getApi(){
var a = false
await fetch('http://127.0.0.1:8088/test')
.then(function(res){
return res.json();
})
.then(function(res){
console.log('request res==',res);
a = res.success;
})
return a
}
function getApi(){
var a = false
return fetch('http://127.0.0.1:8088/test')
.then(function(res){
return res.json();
})
.then(function(res){
console.log('request res==',res);
a = res.success;
return a
})
}
var b = getApi();
b.then((res)=>{
console.log(res);
})
console.log('b====',b);