欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

ES6/7学习之async/await

程序员文章站 2022-03-08 23:37:28
...
  1. async 函数返回一个 Promise 对象,可以使用 then 方法添加回调函数。
  2. async 函数中可能会有 await 表达式,async 函数执行时,如果遇到 await 就会先暂停执行 ,等到触发的异步操作完成后,恢复 async 函数的执行并返回解析值。
  3. await 操作符用于等待一个 Promise 对象或者任何要等待的值,仅在 async function 中有效。如果在 async function 函数体外使用 await ,你只会得到一个语法错误。
  4. 如果一个 Promise 被传递给一个 await 操作符,await 将等待 Promise 正常处理完成并返回其处理结果
  5. 如果await等待的不是 Promise 对象,则返回该值本身。
  6. await意味着让出线程的操作
  7. async会返回Promise对象,如果返回值不是Promise对象则调用Promise.resolve来转换成Promise对象
  8. 执行栈执行完毕后,会回到队列中,执行async函数里后续的语句

如果遇到 await 就会先暂停执行
遇到await依然会执行await等待的内容,然后跳出函数继续执行同步代码(让出线程),执行完再回来继续执行。

async function async1() {
    console.log('async1');
    await async2();
    console.log('async1 end')
}
async function async2() {
    console.log('async2')
}
async1();
console.log('script end')
/*输出:
async1
async2
script end
async1 end
*/
async function async1() {
    console.log('async1');
	var num = await 1;
	console.log(num);
    console.log('async1 end')
}
async1();
console.log('script end')
/*输出:
async1
script end
1
async1 end
*/

await 将等待 Promise 正常处理完成并返回其处理结果
promise状态未完成,则会一直等待

async function async1() {
    console.log('async1');
    await async2();
    console.log('async1 end')
}
async function async2() {
    console.log('async2')
    return new Promise((resolve,reject)=>{
    	console.log('promise pending')
	})
}
async1();
console.log('script end')
/*输出:
async1
async2
promise pending
script end
*/
async function async1() {
    console.log('async1');
    await async2();
    console.log('async1 end')
}
async function async2() {
    console.log('async2')
    return new Promise((resolve,reject)=>{
    	console.log('promise pending')
    	resolve(); // 增加了这条
	})
}
async1();
console.log('script end')
/*输出:
async1
async2
promise pending
script end
async1 end
*/
async function async1() {
    console.log('async1');
    var a = await async2();
    console.log('async1 end')
}
async function async2() {
    console.log('async2')
    return new Promise((resolve,reject)=>{
        console.log('async2 promise')
        resolve();
    }).then(value=>{
        console.log('async2 promise then')
    })
}
async1();
new Promise((resolve,reject)=>{
    console.log('promise')
    resolve();
}).then(value=>{
    console.log('promise then')
})

console.log('script end')
/*输出:
async1
async2
async2 promise
promise
script end
async2 promise then
promise then
async1 end
*/

参考:
前端er,你真的会用 async 吗? (此参考中顺序示例讲解有误,主要理解原理)
ES6 async 函数

相关标签: ES6/7 es6/es7