一、通过 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();