I have 2 function getAccountInfo() and getAdjustmentsInfo(accountInfo) they both return a new promise. The only different is that the second function needs the information returned from the first function.
I tried to declare these 2 function first, and call them one by one using then(). But it is not working as I expected.
These are the functions, as you can see the second function needs account_code from the first accountInfo object:
function getAccountInfo() {
return new Promise((resolve, reject) => {
getAccountCallbackFunc((errResponse, response) => {
if (errResponse) {
return reject(errResponse);
}
resolve(response);
});
});
}
function getAdjustmentsInfo(accountInfo) {
return new Promise((resolve, reject) => {
getAdjustmentCallbackFunc(accountInfo[0].account_code, function (errResponse, response) {
if (errResponse) {
reject(errResponse);
}
if (response) {
resolve(response);
}
});
});
}
This is the controller code to call the functions:
var accountInfo = {};
getAccountInfo()
.then(response => {
accountInfo = response.data.accounts.account;
console.log(accountInfo);
})
.then(getAdjustmentsInfo(accountInfo))
.catch(err => console.log(err));
So I run the getAccountInfo() function first and run the first then() to saved the account information to the external variable accountInfo. Next I run the second then() trying to pass the accountInfo to the second function, which is not working, the second function never got called. Is that something I am missing? Please let me know.
There are couple of mistakes in your code. First is that you are not returning anything nor resolving any promise in the line accountInfo = response.data.accounts.account;console.log(accountInfo);
so the .then(getAdjustmentsInfo(accountInfo))
will not be called. Secondly, i suppose the first argument to a .then()
is always a callback with the first argument being something that is returned from the previous Promise.
Your function getAccountInfo()
returns a promise. When that promise is resolved you can
directly use that as follows.
var accountInfo = {};
getAccountInfo()
.then(response => {
accountInfo = response.data.accounts.account;
console.log(accountInfo);
getAdjustmentsInfo(accountInfo)
})
.then(resultFromPreviousPromise => {
//Use the resultFromPreviousPromise if wanted else you can skip this .then()
})
.catch(err => console.log(err));