gpt4 book ai didi

node.js - Node 在异步函数完成之前退出

转载 作者:IT老高 更新时间:2023-10-28 23:20:57 27 4
gpt4 key购买 nike

我有一个返回 promise 的函数,我试图在异步函数中等待它。问题是程序立即完成,而不是等待 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 的输出,果然,它编译了同步版本。

我以为我可以等待异步函数中的 promise 。我在这里有什么遗漏吗?

最佳答案

您没有正确使用 Promise(假设它符合标准)。它没有 resolve 方法。你应该传递一个函数:

function doItSlow() {
return new Promise(resolve => {
setTimeout( () => {
console.log( "resolving" );
resolve();
}, 1000 );
});
}

关于node.js - Node 在异步函数完成之前退出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31124968/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com