【发布时间】:2019-12-21 10:23:27
【问题描述】:
我有 2 个函数 getAccountInfo() 和 getAdjustmentsInfo(accountInfo) 他们都返回一个新的承诺。唯一不同的是第二个函数需要第一个函数返回的信息。
我尝试先声明这两个函数,然后使用then()一个一个调用。它有效,但问题是,第二个函数需要第一个承诺的结果。
不仅如此,第一个 Promise 还返回了一个数组,例如一个包含 10 个帐户信息的数组。但是第二个函数只需要账户信息的属性,例如account_code。
所以我想我需要运行第二个函数 10 次..?我不太确定该怎么做。
这些是函数,你可以看到第二个函数需要来自第一个 accountInfo 对象的 account_code:
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);
}
});
});
}
这是调用函数的控制器代码:
var accountInfo = {};
var adjustmentsInfo = {};
getAccountInfo()
.then(response => {
accountInfo = response.data.accounts.account;
getAdjustmentsInfo(accountInfo)
})
.then(response => {
adjustmentsInfo = response.data.adjustments;
})
.catch(err => console.log(err));
我把第二个函数改成这样,下面是我改成的代码,所以它可以循环:
function getAdjustmentsInfo(accountInfo) {
return new Promise((resolve, reject) => {
let result = {};
for(account of accountInfo){
getAdjustmentCallbackFunc(account.account_code, function (errResponse, response) {
if (errResponse) {
reject(errResponse);
}
if (response) {
result += response;
}
});
}
console.log(result);
resolve(result);
});
}
所以我先运行getAccountInfo()函数,再运行第一个then(),将账户信息保存到外部变量accountInfo中。 接下来我运行第二个 then() 尝试将 accountInfo 传递给第二个函数,第二个函数将循环并多次运行内部 getAdjustmentCallbackFunc() 以创建新结果并解决它。我不知道为什么它不起作用。那是我想念的吗?请告诉我。
【问题讨论】:
-
尝试改变
getAdjustmentsInfo(accountInfo)->return getAdjustmentsInfo(accountInfo) -
该循环不起作用,您在循环之后立即调用
resolve()而无需等待回调运行。保留您的第一个版本的getAdjustmentsInfo。如果你真的需要做一些循环,请多次调用getAdjustmentsInfo并了解Promise.all。
标签: javascript node.js recurly