async 与 await 的用法

5,192 阅读1分钟

async:

async 作为一个关键字放到函数之前,表示函数是异步的函数,异步函数也就意味着该函数的执行,不会阻塞后面代码的执行

async函数返回的是一个promise对象

async function testAsync() {
    return 111;
}
console.log(testAsync()); // 返回结果是一个promise对象,而不是 111 
/***
 * Promise
 *   __proto__: Promise
 * [[PromiseStatus]]: "resolved"
 * [[PromiseValue]]: 111
 * 
 */
// async 封装的函数,正确调用方式:
testAsync().then(res => {
  console.log(res); // 111
})

await:

代码需要等待await后面的函数运行完并且有了返回结果之后,才继续执行下面的代码,同步的效果

  • await 是在等待后面表达式的执行结果
  • await 关键字不能单独使用,是需要使用在 async 方法中
  • 阻塞主函数的执行,直到后面的Promise函数返回结果
function testWait() {
    return new Promise((resolve,reject)=>{
        setTimeout(function(){
            console.log("testWait");
            resolve();
        }, 1000);
    })
}
async function testAwaitUse(){
    await testWait()
    console.log("hello");
    return 123;
    // 输出顺序:testWait,hello
    // 不使用await输出顺序:hello , testWait
}
// testAwaitUse();
console.log(testAwaitUse())