3

I need to do something like this:

const fn = () => new Promise((resolve, reject) => {
  const timeout = setTimeout(() => reject('time out!'), 3000);
  doSth().then((d) => {
    clearTimeout(timeout );
    resolve(d);
  }).catch(reject);
});
fn().catch(console.log);

And I want to implement them use async&await:

const fn = async () => {
  const timeout = setTimeout(() => { throw new Error('time out!'); }, 3000);
  return await doSth();
};
try {
  fn();
} catch (e) {
  console.log(e);
}

But, I found that the 'time out!' error throw by the nested function cannot be catch in async version, and if one branch failed, the other would execute continue. Is there any way in async that could throw error in nested function and prevent the whole queue?

@Bergi excuse me, I think it's entirely different question with your. the Promise version has nothing wrong, what puzzle me is, how to catch error witch throwed from nested async function, and how to interrupt all other nested funtion when one of them throw. In Promise version it easy to do that, but could it to do and how to do that with async|await without Promiser ? Is it the only way that use Promise?

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • Avoid the [`Promise` constructor antipattern](https://stackoverflow.com/q/23803743/1048572?What-is-the-promise-construction-antipattern-and-how-to-avoid-it) and you'll be fine. – Bergi Aug 17 '17 at 13:14
  • But no, `async`/`await` is syntactic sugar for `then` calls only and not a replacement for the `new Promise` constructor at promisifying asynchronous callback functions. – Bergi Aug 17 '17 at 13:18

0 Answers0