提问人:ARADHYA MISHRA 提问时间:7/3/2023 更新时间:7/3/2023 访问量:34
return 语句在异步函数的 for 循环中不起作用 [duplicate]
Return statement not working inside for loop in an async function [duplicate]
问:
我必须遍历异步功能中的数组。 该函数似乎不会在 resturn 语句处终止,而是会继续。
我正在使用:
async function f(args){
...
...
...
arr.forEach((z) => {
if (condition)
{
console.log("Should be true");
return true;
}
});
console.log("Should not reach here");
return false;
}
当我调用函数时,控制台记录了两个语句,而返回的值为 false,而它必须为 true。
const res = await f(args);
console.log("RES: ", res);
Should be true
Should not reach here
RES: false;
如果我使用地图,也会发生同样的事情。
答:
0赞
Nils Kähler
7/3/2023
#1
您是从要发送到的胖箭头函数返回的,而不是从您的函数返回的。false return 语句返回函数,因为它不在 forEach 函数的块范围内。true
forEach
f
f
使用 instead 代替 ,因为 your 中的 return 语句不会影响您的包装函数。some
forEach
forEach
some
如果语句返回 true,则返回,否则,如果它遍及所有元素,它将返回 false,然后您可以在包装函数中返回它。可以把它想象成一个“数组中是否存在”函数。
async function f(args) {
...
...
...
return arr.some((z) => {
if (condition) {
console.log("Should be true");
return true;
}
});
}
评论
(z) => {}
function f(args){
forEach