I have some async
function that awaits some promises inside which may get rejected, and I want to pass on all errors to the function's returned promise. Does JS do this automatically?
For example:
async foo(){
bar_result = await bar();
baz_result = await baz();
return 'ok';
}
foo()
.then(console.log)
.catch(console.error);
What would happen in the above example if either bar()
or baz()
get rejected? Intuitively, they would be caught at the .catch(console.error)
line...
My alternative idea is to surround the function's contents in a try
block and then catch(err){ throw err; }
, but it looks redundant...
Inside an async
function, if a Promise is await
ed, and that Promise rejects, the function will immediately terminate, and the Promise that it returned will reject (with the same value of the rejected await
ed promise). Your function will work as desired - if either bar
or baz
rejects, console.error
will result in the rejection being logged (and console.log
will not be called).