英文:
Pass an ASYNC JavaScript function as parameter
问题
我试图将一个异步JS函数作为函数参数传递,但我一直得到一个未定义的响应。我在另一个SO回答中找到了代码,当不使用async/await时可以工作,但当我尝试修改它以允许async/await时,我没有得到嵌套函数的结果"5"。为什么会发生这种情况,我该如何修复它?
期望结果示例(打印"5"):
async function foo(x) {
//sleep 5 sec
await new Promise((resolve) => setTimeout(resolve, 5000));
console.log(x);
return 5
}
async function bar(func) {
console.log(1)
return await func();
console.log(2)
}
(async()=>{
//alerts "Hello World!" (from within bar AFTER being passed)
let keys=await bar(async function(){ await foo("Hello World!") });
console.log(`result:`,keys)
})()
英文:
I am trying to pass an async JS function as a function parameter, but I keep getting an undefined response. I found code in another SO answer which works when not using async/await, but when I tried to modify it to allow async/await I dont get the nested function result "5" returned. Why is this happening, and how can I fix it?
Code example (expected result print "5")
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
async function foo(x) {
//sleep 5 sec
new Promise((resolve) => setTimeout(resolve, 5000));
console.log(x);
return 5
}
async function bar(func) {
console.log(1)
return await func();
console.log(2)
}
(async()=>{
//alerts "Hello World!" (from within bar AFTER being passed)
let keys=await bar(async function(){ await foo("Hello World!") });
console.log(`result:`,keys)
})()
<!-- end snippet -->
答案1
得分: 1
你在 sleep
上缺少了 await
,如果你想让它等待5秒的话。在你传入的函数中没有返回语句,所以函数返回 undefined。
async function foo(x) {
// 等待 5 秒
await new Promise((resolve) => setTimeout(resolve, 5000));
console.log(x);
return 5;
}
async function bar(func) {
console.log(1);
return await func();
console.log(2); // 这一行不会执行,因为前面已经返回了
}
(async () => {
let keys = await bar(async function() {
return await foo("Hello World!");
});
console.log(`result:`, keys);
})();
英文:
You are missing an await
on the sleep if you want it to wait 5 seconds. You have no return in the function you are passing in so the function returns undefined.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
async function foo(x) {
//sleep 5 sec
await new Promise((resolve) => setTimeout(resolve, 5000));
console.log(x);
return 5
}
async function bar(func) {
console.log(1)
return await func();
console.log(2)
}
(async()=>{
let keys=await bar(async function(){ return await foo("Hello World!") });
console.log(`result:`,keys)
})()
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论