gpt4 book ai didi

Javascript 模块化 Promise 链乱序

转载 作者:行者123 更新时间:2023-12-01 03:23:57 28 4
gpt4 key购买 nike

我试图找出为什么我的 Promise 链执行无序,尽管编写了一个非嵌套的 then 链。我的函数已经模块化,以减少链中发生的代码膨胀(我期望有五个 then 方法),并且我不确定这些模块中的某些内容是否导致顺序跳转,或者是否是由于我的原因总体 promise 结构。

这是终端输出:

Executing (a6bf615e-5497-47b2-8aea-3f7d70927cba): START TRANSACTION;
Executing (a6bf615e-5497-47b2-8aea-3f7d70927cba): SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;
Step 1: Document Find
Step 3: Cancel Stripe Subscription
string //console.log(typeof subscriptionId);
sub_jsdfjsdfjdsfjsdfj //console.log(subscriptionId)
Executing (a6bf615e-5497-47b2-8aea-3f7d70927cba): SELECT ....
Step 2: Set Array
[ 13, 14 ] //console.log(documentArr);
undefined //console.log(canceledStripeAccount);
undefined //console.log(canceledAt)

这是我的 promise 结构:

var sequelize = require('sequelize');
var models = require('../../../models/db-index');
var deleteAccount = require('./delete-account');


//DELETE /settings/account
exports.delete = function(req, res){
var documents;
var documentArr;
var canceledStripeAccount;
var canceledAt;

return models.sequelize.transaction().then(function(t){

return deleteAccount.queryAllDocuments(req.session.organizationId, t)
.then(function(_document){
console.log("Step 2: Set Array");
documentArr = _document;
console.log(documentArr);
})
.then(deleteAccount.cancelStripeAccount(req.session.subscriptionId, canceledStripeAccount, canceledAt))
.then(function(canceledStripeAccount){
console.log(canceledStripeAccount);
console.log(canceledAt)
});
});
};

模块文件:

var models = require('../../../models/db-index');
var components = require('./components');
var stripe = require('stripe')(process.env.STRIPE_API_KEY);

module.exports = {

queryAllDocuments: function(organization, t){
console.log("Step 1: Document Find");
return models.Document.findAll({
include: [{
model: models.User,
include: [{
model: models.Organization,
where: {
organizationId: organization
}
}]
}],
transaction: t
})
},

cancelStripeAccount: function(subscriptionId, canceledStripeAccount, canceledAt){
console.log("Step 3: Cancel Stripe Subscription");
console.log(typeof subscriptionId);
console.log(subscriptionId)
return stripe.subscriptions.del(subscriptionId).then(function(_canceledStripeAccount){
return canceledStripeAccount = _canceledStripeAccount;
//canceledAt = canceledStripeAccount.canceled_at;
})
}

}

最佳答案

您在 .then() 甚至调用其回调之前直接调用该函数(并将返回值从该函数传递给 .then()):

.then(deleteAccount.cancelStripeAccount(req.session.subscriptionId, 
canceledStripeAccount, canceledAt))

相反,.then() 应该传递一个函数引用,以便它可以稍后调用该函数:

.then(() => deleteAccount.cancelStripeAccount(req.session.subscriptionId,
canceledStripeAccount, canceledAt))

关于Javascript 模块化 Promise 链乱序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44960658/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com