异步await执行结果

console.log('A')
async function getAllFile(){
console.log('B')
const r1 = await thenFs.readFile('./files/1.txt','utf8')
const r2 = await thenFs.readFile('./files/2.txt','utf8')
const r3 = await thenFs.readFile('./files/3.txt','utf8')
console.log(r1,r2,r3)
console.log('D')
}
getAllFile()
console.log('C')

正确执行结果:A B C r1 r2 r3 D

理解: await等到之后,如果不是promise,await会阻塞后面的代码,先执行async外面的同步代码,同步代码执行完,再回到async内部,把这个非promise的东西,作为await表达式结果。

如果不是promise,await也会暂停async后面的代码,先执行,async外面的同步代码,等着promise对象fulfilled。然后把resolve的参数作为await表达式的运行结果。

碰到await 后边的代码都会异步执行,主线程退出当前方法的执行, 进行同步代码执行,接着主线程再进行异步执行。

async/await中真正起作用的是await,async关键字,无论从哪个方面来看,都不过是一个标识符,毕竟函数如果不包含waait关键字,器质性基本上跟普通函数没有区别。

 

posted @ 2021-10-08 11:16  ajaXJson  阅读(198)  评论(0编辑  收藏  举报