Promise 实例一经创建,执行器立即执行。
new Promise((resolve, reject)=>{
setTimeout(()=>{
resolve('hello');
},10000);
}).then(value=>{
return new Promise((resolve, reject)=>{
.....
});
}).then(value=>{
console.log(value);
}).catch(err=>{
console.log(err);
}).finally(value=>{
});
new Promise(function(resolve, reject){})
.then(function(value){})。Promise里面的函数是立即执行的。等到里面函数调用了resolve函数后,才会调用then中的function。then中默认会返回一个空Promise,此promise会默认立即执行resolve。也可以自己return一个promise,等此Promise中调用了resolve后才会继续队列中的then。
批量执行
Promise.all([p1,p2,p3]);
当所有子Promise都完成,该Promise完成,返回值是全部值的数组。
有任何一个失败,该Promise失败,返回值是第一个失败的子Promise的结果。
Promise.race([p1,p2,p3]);
区别在于,它只要有一个完成就算完成。
常见用法。
把异步操作和定时器放在一起。
如果定时器先触发,就认为超时,告知用户。
把回调包装成Promise
有两个好处,1.可读性更好。2,返回的结果可以加入任何Promise队列。
async
async
函数返回一个 Promise 对象,可以使用then
方法添加回调函数。当函数执行的时候,一旦遇到await
就会先返回,等到异步操作完成,再接着执行函数体内后面的语句。
async
函数内部return
语句返回的值,会成为then
方法回调函数的参数。
function timeout(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
async function asyncPrint(value, ms) {
await timeout(ms);
console.log(value);
}
asyncPrint('hello world', 50);
处理异常。
async function f() {
await Promise.reject('出错了')
.catch(e => console.log(e));
return await Promise.resolve('hello world');
}
f()
.then(v => console.log(v))
// 出错了
// hello world
如果有多个await
命令,可以统一放在try...catch
结构中。
async function main() {
try {
const val1 = await firstStep();
const val2 = await secondStep(val1);
const val3 = await thirdStep(val1, val2);
console.log('Final: ', val3);
}
catch (err) {
console.error(err);
}
}
await
命令后面的Promise
对象,运行结果可能是rejected
,所以最好把await
命令放在try...catch
代码块中。
await
命令只能用在async
函数之中,如果用在普通函数,就会报错。