I make a call to async function in a loop like this (something like upload list of files):
return new Promise(async function(resolve, reject) {
for (let i = 0; i < list.length; i++) {
let response = await myAsyncFunction();
if (response.ok === false) {
resolve({error: "Something goes wrong"});
// break; - is this required?
}
}
}
async function myAsyncFunction() {
return new Promise(async function(resolve, reject) {
resolve code....
}
}
If in a loop which is also in a promise I call resolve()
will loop continue to iterate or it will stop there.
Basically do I need to call break;
in loop if I resolve before that?
Will resolve in promise loop break loop iteration?
No, it will not. If you want to break the loop, you have to do that with break
or return
.
But as a separate thing, there are a couple of other problems there:
There's no reason for new Promise
in that code. async
functions return promises, no need to wrap them.
Using an error flag with resolution is generally not best practice. Use rejection to signal failure, not fulfillment with an error code.
So:
return (async function(resolve, reject) {
for (let i = 0; i < list.length; i++) {
let response = await myAsyncFunction();
if (response.ok === false) { // I'd use `if (!response.ok) {`
throw new Error("something goes wrong");
}
}
// Presumably return something here
})();
(That looks a bit awkward. If you provide more context, it may be possible to make it look less awkward.)
Similarly, myAsyncFunction
either A) Shouldn't be an async
function, or B) Shouldn't use new Promise
. See What is the explicit promise construction antipattern and how do I avoid it?
Finally, this is suspect:
let response = await myAsyncFunction();
if (response.ok === false) { // I'd use `if (!response.ok) {`
throw new Error("something goes wrong");
}
Unless there's a very good reason, myAsyncFunction
should reject, not fulfill, its promise when there's a problem. (The hundreds of thousands of examples of incorrect code using fetch
without checking response.ok
is testament to that.)