Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will resolve in promise loop break loop iteration?

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?

like image 434
1110 Avatar asked Oct 14 '25 14:10

1110


2 Answers

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:

  1. There's no reason for new Promise in that code. async functions return promises, no need to wrap them.

  2. 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.)

like image 158
T.J. Crowder Avatar answered Oct 17 '25 03:10

T.J. Crowder


Resolve will break loop or even nested loops, as I see from this code:

function loops() {
  return new Promise((resolve, reject) => {
    for (let i = 0; i < 10; i++) {
      for (let j = 0; j < 10; j++) {
        if (j === 1) {
          resolve("first");
        }

        if (j === 5) {
          resolve("second");
        }
      }
    }
    resolve("third");
  });
}

async function execute() {
  let test = await loops();
  console.log(test);
}

execute();
like image 43
Romikas Avatar answered Oct 17 '25 03:10

Romikas