在 async 函数中使用 await 关键字等待 promise 对象的结果返回,并确保在调用 resolve() 或 reject() 函数之前,不要想异步函数中添加其他的异步操作代码,否则可能会导致“async/await continuing too soon”错误的发生。
示例代码:
async function doSomething() { const result1 = await someAsyncCall1(); const result2 = await someAsyncCall2(); // 此处代码不会过早执行,因为前面已经使用了 await 关键字等待上一个 promise 的返回结果 const result3 = await someAsyncCall3(); // 同上 console.log(result1, result2, result3); return 'Done!'; }
function triggerAsyncOperation() { const promise = doSomething(); promise.then((result) => { console.log('Async operation completed:', result); }).catch((error) => { console.error('Async operation failed:', error); }); }