Working With Promises Inside An If/else
Solution 1:
If you can use async/await
asyncfunctionsomeFunc() {
var more_code = function () {
// more code
}
if (shoud_do_thing_a) {
awaitdo_thing_a()
} else {
awaitdo_thing_b()
}
more_code()
}
Or if you can't, use then()
:
var more_code = function () {
// more code
}
var do_thing;
if (shoud_do_thing_a) {
do_thing = do_thing_a()
} else {
do_thing = do_thing_b()
}
do_thing.then(more_code)
Solution 2:
If you're stuck with raw Promises and can't use async/await
(You usually should have no trouble, what with babel/typescript etc), the following is a bit more elegant than storing the promise in a variable:
functionsomething() {
returnPromise.resolve()
.then(() => {
if (should_do_thing_a) {
returndo_thing_a();
}
elseif (should_do_thing_b) {
returndo_thing_b();
}
})
.then(some_more_code);
}
Note that when you start working with Promises, your functions should always return a Promise that other functions can work with. Leaving an asynchronous action without any way to handle it means bad things, especially when it comes to error handling.
In a more general sense, it means that when you use Promises, more of your code is "uplifted" into being executed and returned as Promises.
Solution 3:
How I want to improve on other answers:
- keep it clean and simple
- no unneeded variables
- return promise asap
- in js we use camelCase
- put it in a function and name that function to keep it readable
- let
then
executemoreCode
so it's called after the thing is done.
function doTheThing () {
if (shouldDoA) return doThingA()
else return doThingB()
}
doTheThing().then(moreCode)
Solution 4:
Simple working example:
The scope it's defined in must be async.
const createUser = async (data) => {
if (await isUsernameTaken(username)) { return'username-taken' }
}
The isUsernameTaken func:
const isUsernameTaken = async (username) => {
const request = await API.SomeRequest
return !request.isEmpty
}
Solution 5:
Save the promise and add the then after the if statement:
var promise;
if (shoud_do_thing_a) {
promise = do_thing_a();
} else {
promise = do_thing_b();
}
promise.then(more_code);
Post a Comment for "Working With Promises Inside An If/else"