1. 程式人生 > >vue:非同步async and await

vue:非同步async and await

async 非同步,會再最後執行

async function timeout() {
    return 'hello world'
}
console.log(timeout());
console.log('先執行');

如果async 函式中有返回一個值 ,當呼叫該函式時,內部會呼叫Promise.solve() 方法把它轉化成一個promise 物件作為返回

async function timeout(flag) {
    if (flag) {
        return 'hello world'
    } else {
        throw 'my god, failure'
    }
}
console.log(timeout(true))  // 呼叫Promise.resolve() 返回promise 物件。
console.log(timeout(false)); // 呼叫Promise.reject() 返回promise 物件。

await

async function testResult() {
    let first = await doubleAfter2seconds(30);
    let second = await doubleAfter2seconds(50);
    let third = await doubleAfter2seconds(30);
    console.log(first + second + third);
}

6秒後,輸出220
必須等完成後才執行下一步