I'm using this library to chain asynchronous functions in my nodejs app:
var chain = async(function(){
var foo = await(bar());
var foo2 = await(bar2());
var foo3 = await(bar2());
}
So bar3 waits for bar2 to finish and bar2 waits for bar() to finish. That's fine. But what will I do in order to stop the async block from further execution? I mean something like this:
var chain = async(function(){
var foo = await(bar());
if(!foo){return false;} // if bar returned false, quit the async block
var foo2 = await(bar2());
var foo3 = await(bar2());
}
what's the best approach to handle this?
at the moment I throw an exception within bar and handle the exception in way:
chain().catch(function (err) { //handler, ie log message)
It's working, but it doesn't look right
I'm using this library to chain asynchronous functions in my nodejs app: https://github./yortus/asyncawait
var chain = async(function(){
var foo = await(bar());
var foo2 = await(bar2());
var foo3 = await(bar2());
}
So bar3 waits for bar2 to finish and bar2 waits for bar() to finish. That's fine. But what will I do in order to stop the async block from further execution? I mean something like this:
var chain = async(function(){
var foo = await(bar());
if(!foo){return false;} // if bar returned false, quit the async block
var foo2 = await(bar2());
var foo3 = await(bar2());
}
what's the best approach to handle this?
at the moment I throw an exception within bar and handle the exception in way:
chain().catch(function (err) { //handler, ie log message)
It's working, but it doesn't look right
Share Improve this question edited Jul 10, 2015 at 15:46 Martijn Pieters 1.1m321 gold badges4.2k silver badges3.4k bronze badges asked Mar 3, 2015 at 15:37 Artur StaryArtur Stary 7442 gold badges14 silver badges31 bronze badges 1-
Doesn't
return false
as you wrote it just work? – Bergi Commented Mar 3, 2015 at 16:32
2 Answers
Reset to default 6I mean something like this …
asyncawait supports exactly this syntax. Just return
from the function:
var chain = async(function(){
var foo = await(bar());
if (!foo) return;
var foo2 = await(bar2());
var foo3 = await(bar2());
});
As an alternative to the accepted answer, and depending on your usage, you may want your bar()
s to throw
/reject.
async function bar() {
try {
Api.fetch(...) // `fetch` is a Promise
} catch (err) {
// custom error handling
throw new Error() // so that the caller will break out of its `try`
// or re-throw the error that you caught, for the caller to use
throw err
}
// or, instead of a try/catch here, you can just return the Promise
return Api.fetch(...)
}
var chain = async(function(){
try {
// if any of these throw or reject, we'll exit the `try` block
var foo = await(bar());
var foo2 = await(bar2());
var foo3 = await(bar2());
} catch {} // ES2019 optional catch. may need to configure eslint to be happy
});