【发布时间】:2015-06-29 20:28:46
【问题描述】:
我有一个返回 Promise 的函数,我正试图从一个异步函数中等待它。问题是程序立即完成,而不是等待承诺。
异步测试.js:
function doItSlow() {
const deferred = new Promise();
setTimeout( () => {
console.log( "resolving" );
deferred.resolve();
}, 1000 );
return deferred;
}
async function waitForIt( done ) {
console.log( "awaiting" );
await doItSlow();
console.log( "awaited" );
done();
}
waitForIt(() => {
console.log( "completed test" );
});
console.log( "passed by the test" );
构建并运行:
babel --stage 0 --optional runtime async-test.js > at.js && node at.js`
结果:
awaiting
passed by the test
立即解决而不是等待一秒钟没有效果:
function doItSlow() {
const deferred = new Promise();
console.log( "resolving" );
deferred.resolve();
return deferred;
}
有趣的是,“resolving”永远不会被打印出来,即使它现在是同步的:
awaiting
passed by the test
我怀疑是编译器问题,但我检查了 Babel 的输出,果然,它确实编译了同步版本。
我以为我可以等待异步函数中的承诺。我在这里有什么遗漏吗?
【问题讨论】:
标签: node.js async-await babeljs ecmascript-2016