我有一个由数据库查询和 API 调用组成的 promise 链。我正在尝试运行这些进程,然后将它们存储为可以在 View 中使用的对象,但似乎我的链渲染最后一步的速度比从 stripe.customers.retrieve 部分提取值的速度快,这阻止了我恢复该方法返回的对象。例如,请参见终端输出部分。这可能是我对 Promise 的误解,但是链接不应该按从上到下的顺序调用项目吗?有没有办法防止在 stripe.customers.retrieve
完成之前渲染最后一个链?
promise 链:
var account;
var card;
var customerInfo;
var test;
models.Account.findOne({
...
}).then(function(_account){
console.log('Here is the account: ' + _account);
account = _account;
return stripe.customers.retrieveCard(account.customerId, account.cardId, {
function(err, account){
if (err){
return console.log(err);
} else {
return console.log(account);
}
}
}).then(function(_card){
console.log('Here is the card: ' + _card);
card = _card;
return stripe.customers.retrieve(account.customerId, function(err, customer){
if (err){
return console.log(err);
} else {
return console.log('Customer is returned ' + customer)
}
}).then(function(_customer){
customerInfo = _customer;
console.log('Returned value ' + _customer);
console.log('Current card' + card);
console.log('Current customer ' + customerInfo);
res.render('pages/app/settings-billing.hbs', {
...
});
});
});
}).catch(function(err){
console.log(err);
});
终端输出:
Here is the account: [object SequelizeInstance:account]
Here is the card: [object Object]
Returned value undefined
Current card[object Object]
Current customer undefined
Customer is returned [object Object]
最佳答案
在每个 strip 方法上使用 then()
而不是回调,以便从每个方法返回一个 promise 。
对此进行了一些修改,以继续将一个对象传递到最后,而不是使用全局变量
models.Account.findOne({
...
})
.then(function(_account) {
let data = {
account: _account
}
return stripe.customers.retrieveCard(_account.customerId, _account.cardId).then(function(card) {
data.card = card;
return data;
});
})
.then(function(data) {
console.log('Here is the card: ' + data.card);
return stripe.customers.retrieve(data.account.customerId).then(function(customer) {
data.customer = customer;
return data
});
})
.then(function(data) {
console.log(JSON.stringify(data, null, ' '));
}).catch(function(err) {
console.log(err);
});
关于javascript - JS Promises - 链结束在链步骤之前返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43574637/