3

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?

1110
  • 7,829
  • 55
  • 176
  • 334
  • 2
    Why would you return a `Promise` from an `async` function? [`async` returns a promise by default, so you can code it just like a normal function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function). – GBrandt Mar 17 '19 at 12:59
  • 1
    [Never pass an `async function` as the executor to `new Promise`](https://stackoverflow.com/q/43036229/1048572)! – Bergi Mar 17 '19 at 13:53

3 Answers3

5

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

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Hi thanks for pointing to my bad understand of this. I am trying to refactor my code now. So if you can take a look here: https://stackoverflow.com/questions/55208718/when-return-from-awaited-async-function-i-am-getting-undefined – 1110 Mar 17 '19 at 15:31
1

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();
Romikas
  • 73
  • 1
  • 6
0

Don't use Promise constructors & async functions at the same time. That will only cause headaches like this one. Just use an async function, then it becomes clear that you can actually just return:

 return (async function() { // IIFE is all you need, will result in a Promise itself
   for (let i = 0; i < list.length; i++) {
     let response = await myAsyncFunction();
     if (response.ok === false) {
       return {error: "Something goes wrong"};
     }
   }
})();

Read on

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151