首页 > 其他 > 详细

async/await 的使用

时间:2020-07-14 17:59:00      阅读:60      评论:0      收藏:0      [点我收藏+]

1.await 只能出现在 async 函数中

2.

await 等到了它要等的东西,一个 Promise 对象,或者其它值,然后呢?我不得不先说,await 是个运算符,用于组成表达式,await 表达式的运算结果取决于它等的东西。

如果它等到的不是一个 Promise 对象,那 await 表达式的运算结果就是它等到的东西。

如果它等到的是一个 Promise 对象,await 就忙起来了,它会阻塞后面的代码,等着 Promise 对象 resolve,然后得到 resolve 的值,作为 await 表达式的运算结果。

3.

function getSomething() {
    return "something";
}

async function testAsync() {
   // return Promise.resolve("hello async");

    return new Promise(resolve => {
      setTimeout(() => resolve("long_time_value"), 3000);
    });

}

async function test() {
    const v1 = await getSomething();
    const v2 = await testAsync();
    console.log(v1, v2);
}

test();




function takeLongTime() {
return new Promise(resolve => {
setTimeout(() => resolve("long_time_value"), 1000);
});
}


async function test() {
const v = await takeLongTime();
console.log(v);
}


test();




 

 

 

 

 

 

 

 

 

 


链接:https://segmentfault.com/a/1190000007535316

async/await 的使用

原文:https://www.cnblogs.com/ygyy/p/13299696.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!