I have a couple of JavaScript functions that call ajax promises to populate fields. Like this:
var functionA = function () {
//Prepare data for ajax service call
service.getDataA()
.then((data) => $("#inputA").val(data));
}
var functionB = function () {
//Prepare data for ajax service call
service.getDataB()
.then((data) => $("#inputB").val(data));
}
Here are the ajax
var getDataA = function () {
return $.ajax({
type: "GET",
url: url,
data: data,
});
};
var getDataB = function () {
return $.ajax({
type: "GET",
url: `url,
data: data,
});
};
So far, so good.
The issue is, I have a third function, functionC, that depends on the completion of functionA and functionB. I need functionC to execute when both functionA and functionB are complete. I have tried several ways to try to achieve this, with no success.
How do I accomplish something like this?
When functionA and functionB are done
.Then functionC.
3
Answers
As Daniel has said in the comments.
Promise.all
is the best solution. If you cannot use it for some reason, a pattern that could work is the following:You can adapt this to contain
returnStates
differently, wrap it intryC
, or use a global state management tool. This mimicsredux-thunk
essentially without the redux or the thunk.You could use Promise.all, example:
Promise.all() is the guy, something like this: