I have a code that looks something like this
class foo {
constructor() {
// calling a, b, c synchronously
a().then(
function(response) {
b().then(
function(response) {
c();
}, function(error) {
// pass
}
);
}, function(error) {
// pass
}
);
}
a() {
return new Promise(function(fullfill, reject) {
// x is any function that returns a promise, making the
// implementation of this function "a" asynchronous
x().then(
function(response) {
fullfill(response);
}, function(error) {
reject(error);
}
);
});
}
b() {
return new Promise(function(fullfill, reject) {
// x is any function that returns a promise, making the
// implementation of this function "b" asynchronous
x().then(
function(response) {
fullfill(response);
}, function(error) {
reject(error);
}
);
});
}
c() {
// do something
}
}
Basically, I have two functions a and b which are both asynchronous.
These functions are asynchronous because they both call some function x which returns a promise (in my case, it is a query to a database).
I need to call a, followed by b followed by c but sequentially. One way of doing so is what I have implemented in the code above, but it results in nasty nested promise responses.
Is there any other way that I can achieve this same result, without using the following syntax (because if this is the only possible solution, then I might as well not use it at all).
a,bandcare functions that I have written. But they all make queries to a database and these queries are asynchronous. And I have no control over these queries.a().then(b).then(c);.x()has a.then()then it's already a promise. DO NOT create a promise yourself in this case, just doa() {return x()}. That's all. Only ifx()does not return a promise (don't have a.then()) should you create a promise yourself.