定义
我理解的async可以用来修饰函数, 也可以修饰函数表达式. 有async函数, 他是AsyncFunction
构造函数的实例. 他其实是generator的语法糖, async 函数就是将 Generator 函数的星号(*)替换成 async,将 yield 替换成 await,仅此而已。多说一嘴, 虽然看起来一样, 但是他内部自带执行器, 不需要像generator还得自己去实现自执行器.
作用
用来更好的处理异步, 包装promise , 而无需刻意地链式调用promise
。
知识点
async function fn1(){
return 1
}
与下面这个等价
async function fn1(){
return Promise.resolve(1)
}
await 搭配async, 为了保证异步的顺序的
await 命令后面的 Promise 对象
搭配mdn的一个例子
developer.mozilla.org/zh-CN/docs/…
var resolveAfter2Seconds = function() {
console.log("starting slow promise");
return new Promise(resolve => {
setTimeout(function() {
resolve("slow");
console.log("slow promise is done");
}, 2000);
});
};
var resolveAfter1Second = function() {
console.log("starting fast promise");
return new Promise(resolve => {
setTimeout(function() {
resolve("fast");
console.log("fast promise is done");
}, 1000);
});
};
var sequentialStart = async function() {
console.log('==SEQUENTIAL START==');
// 1. Execution gets here almost instantly
const slow = await resolveAfter2Seconds();
console.log(slow); // 2. this runs 2 seconds after 1.
const fast = await resolveAfter1Second();
console.log(fast); // 3. this runs 3 seconds after 1.
}
sequentialStart() // 这个会有顺序的执行完 先执行慢的, 再执行快的, 总共需要3s
var concurrentStart = async function() {
console.log('==CONCURRENT START with await==');
const slow = resolveAfter2Seconds(); // starts timer immediately
const fast = resolveAfter1Second(); // starts timer immediately
// 1. Execution gets here almost instantly
console.log(await slow); // 2. this runs 2 seconds after 1.
console.log(await fast); // 3. this runs 2 seconds after 1., immediately after 2., since fast is already resolved
}
// 这个会同时执行, 总共用2s, 快的先执行完, 但最后的打印顺序是还是哪个await在前, 先打印哪个
小知识点:
promise的构造函数是同步的, 他的then方法是异步的