Cod*_*iot 2 javascript asynchronous node.js promise
我正在学习更多关于 JavaScript 承诺的知识,并在尝试将一些来自不同函数的承诺逻辑组合成一个内联函数时遇到了一个问题。当我将它全部放入一个内联函数中时,它会导致 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';
}
Run Code Online (Sandbox Code Playgroud)
[不工作 - 承诺响应的结果是“未定义”而不是“世界”...]
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)
})
Run Code Online (Sandbox Code Playgroud)
[不工作 - 承诺响应的结果是“未定义”而不是“世界”...]
var helloResult = async () => {
await new Promise(r => {
setTimeout(r, 3000);
return 'world';
})
.then((responseData)=> {
console.log('COMPLETED Promise Result (Promise completed): ' + responseData)
})};
Run Code Online (Sandbox Code Playgroud)
出于某种原因,第二次 2 尝试更改代码的承诺导致“未定义”而不是“世界”返回结果的预期值。
感谢您的任何建议,感谢您的帮助。
Promise在后面的示例中,您正在从构造函数回调中返回。该值未解析。您必须调用resolve回调才能传递值。
await new Promise(r => {
setTimeout(() => r('world'), 3000);
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
372 次 |
| 最近记录: |