blog
blog copied to clipboard
我对 async/await 和 promise 的思考——2018年12月16号
阅读时间约为1m 30s
async/await 和 promise
抛砖引玉
async function series() {
await wait(500);
await wait(500);
return "done!";
}
以上代码执行完毕需要 1000 毫秒,再看看这段代码:
async function parallel() {
const wait1 = wait(500);
const wait2 = wait(500);
await wait1;
await wait2;
return "done!";
}
…以上代码只需 500 毫秒就可执行完毕,因为两个 wait 是同时发生的
async 和 await 到底干了啥?
-
我知道的基本概念
- async 是“异步”的简写,而 await 可以认为是 async wait 的简写。所以意识差不多 async 用于申明一个 function 是异步的,而 await 用于等待一个异步方法执行完成。
- await 只能出现在 async 函数中
-
async 一个函数声明时如果加了async 那么这个函数发生了什么变化?
async function test() {
return 'hello world'
}
test()
//结果:Promise {<resolved>: "hello world"}
//可想而知下面的结果输出什么
test().then((res)=> {consloe.log(res)})
看下面这个例子
function timeout(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
async function asyncPrint(value, ms) {
await timeout(ms);
console.log(value);
}
asyncPrint('hello world', 1000);
一旦遇到await就立刻让出线程,阻塞后面的代码 这句话到底是什么意思
这段代码会等待1s后输出hello world,那我们由此可以看出await在等待一个promise的返回值或者说await等的是右侧「表达式」的结果,并且是从右向左的执行 当碰到await时才让出线程
思考:一个面试题
async function async1() {
console.log( 'async1 start' )
await async2()
console.log( 'async1 end' )
}
async function async2() {
console.log( 'async2' )
}
console.log( 'script start' )
setTimeout( function () {
console.log( 'setTimeout' )
}, 0 )
async1();
new Promise( function ( resolve ) {
console.log( 'promise1' )
resolve();
} ).then( function () {
console.log( 'promise2' )
} )
console.log( 'script end' )