最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Will resolve in promise loop break loop iteration? - Stack Overflow

programmeradmin2浏览0评论

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?

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?

Share Improve this question asked Mar 17, 2019 at 12:52 11101110 6,83956 gold badges186 silver badges346 bronze badges 2
  • 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. – GBrandt Commented Mar 17, 2019 at 12:59
  • 1 Never pass an async function as the executor to new Promise! – Bergi Commented Mar 17, 2019 at 13:53
Add a ment  | 

3 Answers 3

Reset to default 6

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

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

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 bees 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

发布评论

评论列表(0)

  1. 暂无评论