我正在努力学习更多关于 JavaScript promises 的知识,但在尝试将来自单独函数的一些 promise 逻辑组合到单个内联函数中时遇到了一个问题。当我将其全部拉入单个内联函数时,它会导致 promise 返回结果为“未定义”,而不是预期的“世界”值。
[按预期工作,异步解决 promise ,并为 promise 响应生成“世界”]
app.get('/asyncTest', (request, response) => {
console.log("Request started...");
var helloResult = hello()
.then((res)=> {
console.log('COMPLETED Promise Result (Promise completed): ' + res)
});
console.log('Hello Result (immediately after issuing the promise [still in promise object format]): ' + helloResult);
console.log('Mesage at the end of the request (Should fire before completion of the promise result being fulfilled...');
});
function wait(ms) {
return new Promise(r => setTimeout(r, ms));
}
async function hello() {
await wait(3000);
return 'world';
}
[不工作 - promise 响应的结果是“未定义”而不是“世界”...]
var helloResult = async (r) => {
await new Promise(r => {
setTimeout(r, 3000);
return 'world';
})
};
let helloResponse = helloResult().then((res)=> {
console.log('COMPLETED Promise Result (Promise completed): ' + res)
})
[不工作—— promise 响应的结果是“未定义”而不是“世界”……]
var helloResult = async () => {
await new Promise(r => {
setTimeout(r, 3000);
return 'world';
})
.then((responseData)=> {
console.log('COMPLETED Promise Result (Promise completed): ' + responseData)
})};
出于某种原因,在后 2 次更改代码的尝试中, promise 的结果是“未定义”,而不是“世界”返回结果的预期值。
如有任何建议,我们将不胜感激,感谢您的帮助。
最佳答案
在后面的示例中,您将从 Promise
构造函数回调返回。该值未解析。您必须调用 resolve
回调才能传递值。
await new Promise(r => {
setTimeout(() => r('world'), 3000);
});
关于javascript - 需要了解为什么内联函数的 Promise 结果未解析为预期的返回结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57165432/