I'm trying out promise chaining but I'm not quite getting it. I have this exercise I'm doing where I have to do the following scenario:
"You are pranking an office member by adding salt to his coffee, you are to check his location with /locate
api, 'locate' can be either of the following:
response.body: 'in the office'
response.body: 'in the kitchen'
You only add salt when he is in the kitchen, so if the response.body returns 'in the kitchen', you salt his coffee with another post api of /addSalt
.
Now there is the final api endpoint in this exercise called /run
where it is invoked when either condition is met:
/locate returns 'in the office'
/addSalt is called.
I tried the following without incorporating any api or json (I would like to though) and it looked something like this:
function myPromiseFunction() {
//Change the resolved value to take a different path
return Promise.resolve(true);
}
function conditionalChaining(value) {
if (value.body === 'in the kitchen') {
//do addSalt then run
return addSalt(salt).then(run);
} else {
//run
return run();
}
}
function locate() {
// fetch http get location, response body is either 'in his office' or 'in the kitchen'
return Promise.resolve(response.body);
}
function addSalt(salt) {
console.log("addSalt");
return Promise.resolve("We added salt");
}
function run() {
console.log("We are running");
return Promise.resolve("Running");
}
myPromiseFunction().then(conditionalChaining).then(function() {
console.log("All done!");
}).
catch(function(e) {
});
I did not get what conditionalChaining
is doing nor myPromiseFunction
. This obviously didn't work but it could help outline what I'm trying to get. Any tips?
I was referencing this: How to handle the if-else in promise then?