用法
在一个函数前面加上关键词async,使得函数总是返回一个 promise;
——「async」关键字会指示 JavaScript 引擎自动将返回值包装在一个已决议(resolved)的 promise 内;
await关键词:只在async函数里有效,
关键字 await让 JavaScript 引擎等待直到 promise 状态完成,然后以完成的结果继续执行
(⚠️这个行为不会耗费 CPU 资源,因为引擎可以同时处理其他任务:执行其他脚本,处理事件等
归根结底:await函数会返回一个promise,所以外面的函数 基于promise.then得到异步结果,基于promise.catch捕获内部catch的错误
更简洁:展平嵌套的promise
/*** 示例一*/function fetch() {return (fetchData().then(() => {return "done"});)}async function fetch() {await fetchData()return "done"};
/**
* 示例二
*/
function fetch() {
return fetchData()
.then(data => {
if (data.moreData) {
return fetchAnotherData(data)
.then(moreData => {
return moreData
})
} else {
return data
}
});
}
async function fetch() {
const data = await fetchData()
if (data.moreData) {
const moreData = await fetchAnotherData(data);
return moreData
} else {
return data
}
};
/**
* 示例三
*/
function fetch() {
return (
fetchData()
.then(value1 => {
return fetchMoreData(value1)
})
.then(value2 => {
return fetchMoreData2(value2)
})
)
}
async function fetch() {
const value1 = await fetchData()
const value2 = await fetchMoreData(value1)
return fetchMoreData2(value2)
};
阻塞情况
0、await关键字只会在后面的执行语句是未有结果状态的promise时,阻塞后面的代码;
(特别指明:1、await后不是promise时会被自动包裹为resolved的promise;
== 0 ==
async function test() {
await setTimeout(() =>console.log(111), 3000)
console.log(222)
}// 222 111
# 解释:await并没有阻塞,因为await setTimeout等效于 await Promise.resolve(setTimeout xx)
== 1 ==
async function test() {
await new Promise(resolve => setTimeout(()=>console.log(111), 1000))
// 如果没有resolve 就不会往下执行
console.log(222)// 未执行
}// 111
# 解释:await 后面跟了显式的promise,但是没有resolve,导致此promise一直是pendding状态从而阻塞
== 2 ==
async function test() {
await new Promise(resolve => setTimeout(()=>resolve(console.log(111)), 1000))
console.log(222)
}// 111 222 正常版本
== 3 ==
async function test() {
await Promise.all([setTimeout(()=>console.log(111),500)]);
console.log(222)
}// 222 111
# 解释:当all的数组元素不是promise的时候 会调用Promise.resolve方法包装
async函数里的return
1、async函数内部return语句返回的值,会成为then方法回调函数的参数。
===> 因为归根结底,async会将内部的代码包裹进一个promise里,所以当调用async函数时,可以通过.then得到函数内部return or resolve/reject的值
async function f() {
return 'hello world';
# 等同于
return await 'hello world';
}
# 得到f返回值的方法1
f().then(v => console.log(v))
# 得到f返回值的方法2
错误与捕获错误
1、async/await 的出现使得 try/catch 就可以捕获同步和异步的错误。
try/catch 能捕获 fetchData() 中的一些 Promise 构造错误,但是不能捕获 JSON.parse 抛出的异常,如果要处理 JSON.parse 抛出的异常,需要添加 catch 函数重复一遍异常处理的逻辑。
function fetch() {
try {
fetchData()
.then(result => {
# 这里的错误 无法被try catch捕获
# 只能在里面再写一层 try ...catch
const data = JSON.parse(result)
})
.catch((err) => {
console.log(err)
})
} catch (err) {
console.log(err)
}
}
如果用async函数 await异步里的错误能自动被catch捕获,无需写两次cacth
async function fetch() {
try {
# 1.捕获JSON.parse错误 2. 捕获fetchData()的reject
const data = JSON.parse(await fetchData())
} catch (err) {
console.log(err)
}
};
2、任何一个await语句后面的 Promise 对象变为reject状态,那么整个async函数都会中断执行
如果想让第一个await 不影响 第二个await:将await包裹在各自的try catch里面,这样错误不会相互干扰
async函数调用者通过.catch捕获错误
那么捕获各自错误的姿势就变成了:
async function asyncTask(cb) {
# 异步函数1的 try...catch
try {
const user = await UserModel.findById(1);
if(!user) return cb('No user found');
} catch(e) {
return cb('Unexpected error occurred');
}
# 异步函数2的 try...catch
try {
const savedTask = await TaskModel({userId: user.id, name: 'Demo Task'});
} catch(e) {
return cb('Error occurred while saving task');
}
if(user.notificationsEnabled) {
try {
await NotificationService.sendNotification(user.id, 'Task Created');
} catch(e) {
return cb('Error while sending notification');
}
}
if(savedTask.assignedUser.id !== user.id) {
try {
await NotificationService.sendNotification(savedTask.assignedUser.id, 'Task was created for you');
} catch(e) {
return cb('Error while sending notification');
}
}
cb(null, savedTask);
}
这样写代码太繁杂了吧。那我们可以考虑写个handle函数 简化这种复杂
// proxyCatch: .then时return [null, data]; .catch时return [err]
import proxyCatch from './proxyCatch.js';
async function asyncTask() {
let err, user, savedTask;
[err, user] = await proxyCatch(UserModel.findById(1));
if(!user) throw new CustomerError('No user found');
[err, savedTask] = await proxyCatch(TaskModel({userId: user.id, name: 'Demo Task'}));
if(err) throw new CustomError('Error occurred while saving task');
if(user.notificationsEnabled) {
const [err] = await proxyCatch(NotificationService.sendNotification(user.id, 'Task Created'));
if (err) console.error('Just log the error and continue flow');
}
}
// proxyCatch.js
export default function proxyCatch(promise) {
return promise.then(data => {
return [null, data];
})
.catch(err => [err]);
}
总结
下面代码可以帮助理解:
== 0 ==
async function test0() {
await setTimeout(() =>console.log(111), 3000)
console.log(222)
}// 222 111
// 问题提出:为啥await没有起作用?await不是返回一个promise,当promise决议后才下一步吗?
== 1 ==
async function test1() {
await new Promise(resolve => setTimeout(()=>console.log(111), 1000))
// 如果没有resolve 就不会往下执行
console.log(222)// 未执行
}// 111
== 2 ==
async function test2() {
await new Promise(resolve => setTimeout(()=>resolve(console.log(111)), 1000))
console.log(222)
}// 111 222 正常版本
== 3 ==
async function test3() {
await Promise.resolve(setTimeout(()=>console.log(111),500));
console.log(222)
}// 222 111 因为 await后面是一个已经resolve的promise 所以直接下一步
== 4 ==
async function test4() {
await Promise.all([setTimeout(()=>console.log(111),500)]);
console.log(222)
}// 222 111 当all的数组元素不是promise的时候 会调用Promise.resolve方法包装 产生与3一样结果
== 5 ==
async function test5(){
await new _Promise(resolve=>setTimeout(()=>resolve(console.log(111)),1000));
console.log(222)
}// 111 222 _Promise是自己模拟的promise
由上,
1、await后跟的函数调用立即被调用(虽然听起来很像废话..
async function test6() {
await setTimeout(()=>console.log(1),1000);
await setTimeout(()=>console.log(2),500);
await console.log(3)
}// 3 2 1
当 await后面跟的不是promise是普通函数的话,后面的普通函数实际上看成由Promise.resolve包裹后执行
再看下面这个例子更清晰:
test7();
async function test7() {
console.log(1)
await console.log(2)
console.log(3)
}
console.log(4)
// 1 2 4 3
test7 等价于 test7_1
test7_1()
async function test7_1() {
console.log(1)
await Promise.resolve(console.log(2));
console.log(3)
}
console.log(4)
// 1 2 4 3
进而等价于 test7_2
function test7_2() {
console.log(1)
Promise.resolve(console.log(2)).then(()=>{console.log(3)})
}
test7_2();
而产生阻塞的情况是:await后面是未被决议的promise对象才会产生阻塞
(如果是自己写的promise也会产生和Promise一样的效果)
补充阻塞情况的代码
test8();
async function test8() {
await new Promise(resolve => {
console.log(1);
setTimeout(() => {
// resolve();
}, 100);
});
// 由于上一个promise未决议,下面的代码不会执行
await new Promise(resolve => {
console.log(2);
setTimeout(() => {
resolve();
}, 100);
});
await console.log(3);
console.log(5); // 5 也不会执行哦
}
// 但并不影响函数外的执行
console.log(6);
输出:1、6
进阶:串行&并行
批量执行一组异步任务,但是不是并行,而是依次执行
已知模拟了一个异步请求的:fetch函数:
const fetch = ({time, id, val}) => {
console.log(`开始执行:函数id: ${id}; 耗费时间: ${time}`);
return new Promise(resolve => {
setTimeout(() => {
console.log(`${id}有结果了`);
resolve(val || id);
}, time);
});
}
串行
async function getData1() {
const res1 = await fetch({time:3000, id:1});
const res2 = await fetch({time:2000, id:2});
const res3 = await fetch({time:1000, id:3});
return [res1, res2, res3];
}
getData().then(res => console.log(res)); // [1, 2, 3]
1有结果了
开始执行:函数id: 2; 耗费时间: 2000
2有结果了
开始执行:函数id: 3; 耗费时间: 1000
3有结果了
[ 1, 2, 3 ]
简单封装一下,使用数组迭代
async function getData2() {
const urls = [{time:3000, id:1},{time:2000, id:2},{time:1000, id:3}];
const res = [];
for (const url of urls) {
const curres = await fetch(url);
res.push(curres);
}
return res;
}
getData2().then(res => console.log(res)); // [1, 2, 3]
开始执行:函数id: 1; 耗费时间: 3000
1有结果了
开始执行:函数id: 2; 耗费时间: 2000
2有结果了
开始执行:函数id: 3; 耗费时间: 1000
3有结果了
这里有个坑,async await放在for..each里是不能串行的,执行结果是并行的效果
详见
async/await遇上foreach
串行 且有依赖关系: 下一个执行的函数入参, 依赖于 上一个异步执行的结果
这里假设有个需求: 实现id相加的函数:计算出一次执行的函数的id之和: 1+2+3
使用reduce:
async function getData3() {
const urls = [{time:3000, id:1, val:1},{time:2000, id:2, val:2}, {time:1000, id:3, val:3}];
const res = urls.reduce(async (accurpromise, curItem) => {
const prev = await accurpromise || 0;
return fetch({
...curItem,
val: prev + curItem.id // val:输入多少 resolve多少;现在将输入改为了:prev+cur 即实现依赖
});
}, Promise.resolve());
return res;// 6: 1+2+3
}
并行
1、使用promise.all
async function getData1() {
const res = Promise.all([
fetch({time:3000, id:1}),
fetch({time:2000, id:2}),
fetch({time:1000, id:3}),
]);
return res;
}
getData1().then(res => console.log(res)); // [1, 2, 3]
同时打印出:(并发)
开始执行:函数id: 1; 耗费时间: 3000
开始执行:函数id: 2; 耗费时间: 2000
开始执行:函数id: 3; 耗费时间: 1000
根据异步时长相继返回结果:
3有结果了
2有结果了
1有结果了
按函数调用顺序组装结果:
[ 1, 2, 3 ]
2、手动执行,再await promise拿到异步结果
async function getData2() {
// const fetch1Promise = fetch({time:3000, id:1});
// const fetch2Promise = fetch({time:2000, id:2});
// const res1 = await fetch1Promise;
// const res2 = await fetch2Promise;
// return [res1, res2];
# 使用数组迭代封装
const res = [];
const urls = [{time:3000, id:1},{time:2000, id:2}];
const promises = urls.map(url => fetch(url));
for (const curp of promises) {
res.push(await curp);
}
return res;
}
getData2().then(res => console.log(res)); // [1, 2, 3]
同时打印出:(并发)
开始执行:函数id: 1; 耗费时间: 3000
开始执行:函数id: 2; 耗费时间: 2000
开始执行:函数id: 3; 耗费时间: 1000
根据异步时长相继返回结果:
3有结果了
2有结果了
1有结果了
按函数调用顺序组装结果:
[ 1, 2, 3 ]
这里还可以扩展一下,不用async函数,普通函数里的promise如何串行
promise串行&并行
小的总结:
async 会取代 Promise 吗?
- async 函数返回一个 Promise 对象
- 面对复杂的异步流程,Promise更灵活
- Promise 本身是一个对象,所以可以在代码中任意传递
比如:请求超时重传、promisify等函数,证明promise的封装能力是await无法取代的
参考
http://javascript.info
https://github.com/mqyqingfeng/Blog/issues/100
http://es6.ruanyifeng.com/#docs/async
