Return statement not working inside for loop in an async function.

huangapple go评论66阅读模式
英文:

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;
    }
  });
}

huangapple
  • 本文由 发表于 2023年7月3日 20:28:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/76604756.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定