天天看點

node.js promise async/await

一、通過 promise 實作 async 函數(函數裡面必須使用return 傳回 promise 對象,否則雖 catch 能夠過得值,但then 裡面的值為 undefined) 

async function test() {
    return new Promise(resolve, reject) {
        setTimeout(function() {
            resolve(1);
            // reject('error message!');
        }, 2000);
    }
}
           
console.log('---------start--------');
test().then(function (val) {
    console.log(`[val_1=${val}]`);
    return val + 1
}).then(function (val) {
    console.log(`[val_2=${val}]`);
}).catch(err => console.log('error: ', err));
console.log('----------end---------');

/** output
---------start--------
----------end---------
[val_1=1]
[val_2=2]
/
           

二、SyntaxError: await is only valid in async function

let res = await test();
// SyntaxError: await is only valid in async function

function start() {
    console.log('start -----------1');
    let res = await test();
    console.log('end ------------');
}

// await 必須放在函數裡面
start();
           

繼續閱讀