英文:
Return statement not working inside for loop in an async function
问题
我必须在异步函数内部迭代一个数组。
该函数似乎在返回语句处不会终止,而是继续执行。
我正在使用:
async function f(args){
...
...
...
arr.forEach((z) => {
if (condition)
{
console.log("应该为真");
return true;
}
});
console.log("不应该到达这里");
return false;
}
当我调用该函数时,控制台记录了这两个语句,但返回的值是false,而应该是true。
const res = await f(args);
console.log("RES: ", res);
应该为真
不应该到达这里
RES: false;
如果我使用map,情况也是一样的。
英文:
I have to iterate over an array inside an async funtion.
The function does not seem to terminate at the resturn statement but continues further.
I am using:
async function f(args){
...
...
...
arr.forEach((z) => {
if (condition)
{
console.log("Should be true");
return true;
}
});
console.log("Should not reach here");
return false;
}
When I call the function with, the console has both the statements logged while the value returned is false when it must be true.
const res = await f(args);
console.log("RES: ", res);
Should be true
Should not reach here
RES: false;
The same thing happens if I use map.
答案1
得分: 0
你从箭头函数中返回了true
,而不是你的f
函数。错误的返回语句返回了你的f
函数,因为它不在forEach
函数的作用域内。
使用some
代替forEach
,因为在你的forEach
中的返回语句不会影响到你的包装函数。
some
会在语句返回true时返回,否则如果它遍历所有元素都返回false,然后你可以在你的包装函数中返回它。把它想象成一个“数组中是否存在这个元素”的函数。
英文:
You are returning true
from the fat arrow function you are sending through to forEach
and not your f
function. The false return statement returns your f
function since it is not inside the block scope of the forEach function.
Use some
instead of forEach
, since the return statement inside your forEach
will not affect your wrapping function.
some
will return if the statement return true, otherwise if it gets throug all elements it will return false, and then you can return that in your wrapping function. Think of it as a "does this exist in the array"-function.
async function f(args) {
...
...
...
return arr.some((z) => {
if (condition) {
console.log("Should be true");
return true;
}
});
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论