1. 程式人生 > 實用技巧 >async/await 的使用

async/await 的使用

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