return 语句在异步函数的 for 循环中不起作用 [duplicate]

Return statement not working inside for loop in an async function [duplicate]

提问人:ARADHYA MISHRA 提问时间:7/3/2023 更新时间:7/3/2023 访问量:34

问:

我必须遍历异步功能中的数组。 该函数似乎不会在 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;

如果我使用地图,也会发生同样的事情。

JavaScript 循环 async-await foreach 返回

评论

1赞 Jaromanda X 7/3/2023
你从不回来(z) => {}function f(args){
3赞 Bergi 7/3/2023
问题不在于异步函数,而在于forEach

答:

0赞 Nils Kähler 7/3/2023 #1

您是从要发送到的胖箭头函数返回的,而不是从您的函数返回的。false return 语句返回函数,因为它不在 forEach 函数的块范围内。trueforEachff

使用 instead 代替 ,因为 your 中的 return 语句不会影响您的包装函数。someforEachforEach

some如果语句返回 true,则返回,否则,如果它遍及所有元素,它将返回 false,然后您可以在包装函数中返回它。可以把它想象成一个“数组中是否存在”函数。

async function f(args) {
  ...
  ...
  ...

  return arr.some((z) => {
    if (condition) {
      console.log("Should be true");
      return true;
    }
  });
}