0

i can use promise.all solute the requirement, just like:

Promise.all(pics.map(e => new Promise((resolve,reject) => {
  var img=new Image();
  img.addEventListener("load",() => { //i need all event handler finish
    imageonload(e);  
    resolve();
  },false);
  img.onerror=(err) => reject(err);
  img.src=e.src; //this call the event handler          
}))).then(() => {       
  // here do something when the event handler finish all.
}))

My question is can we use async/await rewrite the code, because I don/t like brackets hell.

Tamas Szoke
  • 5,426
  • 4
  • 24
  • 39
defend orca
  • 617
  • 7
  • 17
  • Sure. you can change it to `await Promise.all(....); /* here do something when the event handler finish all */`. The context must be an `async` function of course. – Felix Kling Mar 12 '20 at 16:20
  • `Promise.all()` method also returns a single Promise that fulfils when all of the promises passed as an iterable have been fulfilled. So, you can use `await Promise.all(....)` inside an async function. – palaѕн Mar 12 '20 at 16:22
  • You can use `await` to replace the `then` call, yes. You cannot use `await` to replace the `new Promise` call. If you don't like that many nested brackets, refactor the image loading into a named helper function. – Bergi Mar 12 '20 at 16:25
  • thanks, @FelixKling, that can make it clear more. – defend orca Mar 12 '20 at 16:51
  • @palaѕн I don/t need the event handler success, I just want it finish. after all handler finish and then to do something. – defend orca Mar 12 '20 at 16:52
  • @Bergi, now is 2020, does not we have some solution just like es10/11/12/13? and this is not the same question, you just say async/await can/t use in this question. but your question can be solve easy. – defend orca Mar 12 '20 at 16:53
  • @马长昆michaelbergman Nothing about async/await syntax changed in the last 3 years. I'm not sure what you expect. At best, there would be a new web api that replaces the `load` event with a native promise, but the answer to the general question about "*using async/await with event handler*" is still the same. – Bergi Mar 12 '20 at 19:59

0 Answers0