【发布时间】:2017-11-28 14:26:55
【问题描述】:
我正在尝试创建一个名为 pw_array 的数组,将 pw_subscribers 的内容分配给该数组,然后将 pw_array 中的每个对象附加到第二个承诺中的新键值对。我对承诺很陌生,并且在完成这项工作时遇到了很多麻烦。现在,当我在 getCustomers 函数中的第二个承诺中 console.log(pw_customer) 时,它正在返回我想要的。但是当我稍后 console.log(pw_array) 时它是原始数组。
var pw_array = [];
//first promise is working correctly
var getPaywhirlSubscribers = new Promise(function(resolve, reject) {
paywhirl.Subscriptions.getsubscribers({limit:100}, function(error, pw_subscribers) {
Promise.all(JSON.parse(pw_subscribers).forEach(function(pw_subscriber) {
pw_array.push(pw_subscriber);
}))
// console.log(pw_array);
return resolve(pw_array);
});
});
var getGatewayReferences = function(pw_array) {
return new Promise(function(resolve, reject) {
Promise.all(pw_array.forEach(function(pw_customer) {
paywhirl.Customers.getCustomer(pw_customer.customer_id, function(error, customer) {
pw_customer.phone = customer.phone;
pw_customer.address = customer.address;
pw_customer.gateway_reference = customer.gateway_reference;
// this console.log is returning what I want
// console.log(pw_customer);
});
}));
resolve(pw_array);
// console.log(pw_array);
});
};
还有承诺链...
getPaywhirlSubscribers.then(getGatewayReferences).then(function(pw_array) {
// this console.log is returning the original pw_array with pw_subscribers but not with the appended pw_customer keys
console.log(pw_array);
});
【问题讨论】:
-
您是否尝试过使用
pw_array.map而不是pw_array.forEach,并为地图返回paywhirl.Customers.getCustomer(...(我假设这是一个承诺)。这样下一个.then将拥有所有客户。 -
@asosnovsky 是正确的,您只是对
forEach给您的pw_array中的每个项目进行了变异。这些项目当时没有“实时连接”到原始pw_array。你应该使用.map
标签: javascript arrays promise