I’ll be as brief as possible. Here is simple example
function find5 (arr)
{
return new Promise (function (resolve, reject)
{
arr.forEach (
function (el)
{
console.log (el);
if (el == 5)
{
return resolve (true);
}
}
);
return reject (false);
});
}
async function init ()
{
try {
var res = await find5 ([1,2,3,4,5,6,7,8,9,10]);
console.log (res);
} catch (e) {
console.log (e);
}
}
init ();
Here is output: 1 2 3 4 5 6 7 8 9 10 true
I want to exit from function find5
but return resolve (true);
. I think it returns from function (el)
. How do I jump here: return new Promise
?
Need help with code.
4
Answers
It's bad code, I know, but as an option.
You can simplify this a lot using
async
syntax instead of returning an explicit Promise, and by using one of the many super usefulArray
functions that JS has built in (you definitely want to give the list over on the Array docs a read-through, there are way more than you think):And note that the
find5
function shouldn’t be throwing an error just because you can’t find the element (or in Promise terms, should not be rejecting): that’s an "emergency" mechanism for when unexpected things happen. For instance, ifarr
is undefined or it’s not an array, that’s grounds to throw an error, but the array not containing an element5
is not. The code still works, and finishes, it just didn’t see the element so it reportsfalse
.You cannot return inside a
forEach
in javaScript .. So your loop just continues to run. You can read more about that Here Array.prototype.forEach() — You’ll find in the docs:To properly do it, your going to need a
for loop
instead.In JavaScript, when you use the
return
statement inside a callback function like the one you have in theforEach
loop, it doesn’t actually exit the outer function (find5
in this case). Instead, it only exits the current callback function (function (el)
). This is why thereturn resolve(true)
statement does not exit thefind5
function.If you want to exit the
find5
function when you find the value 5 and resolve the promise, you can use afor
loop instead offorEach
, and then you can break out of the loop when the condition is met. Here’s a modified version of your code:With this code, when
el
is equal to 5, it will resolve the promise and then usereturn
to exit thefind5
function, ensuring that it doesn’t continue iterating over the array unnecessarily.