我想通过异步,等待重构 promise 链的代码。我已经将 ORM 用于数据库管理,并且代码是用具有多个中间件的 AWS Lambda 函数编写的。在这种情况下,我必须使用 sequelize 事务遍历多个条目的代码。使用 promise.all() 很容易管理,但需要将其更改为 async await 语法以获得更清晰的代码。
这是我的演示代码。
/* get all invoice where user_id === current logged in user, and where status != "paid" */
db.Invoice.findAll({
where: {
user_id: currentLoggedInUser,
status: {
$ne: "paid"
}
}
}).then(invoices => {
if (!invoices || invoices === null) {
return false;
}
function addScheduledTransactionAttempts(invoice, tryPayOnDate, t) {
return new Promise((resolve, reject) => {
/* check If any ScheduledTransactionAttempts exists for this invoice.id */
db.ScheduledTransactionAttempts.find({
where: {
invoice_id: invoice.id
}
})
.then(function(attempts) {
if (attempts) {
attempts
.destroy({}, {
transaction: t
})
.then(deletedAttempts => {
console.log("Attempts Record Deleted: ", deletedAttempts);
})
.catch(error => {
reject(error);
t.rollback();
});
}
return db.ScheduledTransactionAttempts.create({
invoice_id: invoice.id,
payment_source_id: PaymentMethodId,
try_pay_on_date: tryPayOnDate,
stripe_customer_id: currentLogInStripeCustomerId
}, {
transaction: t
})
.then(function(attempt) {
resolve(attempt.id);
})
.catch(error => {
reject(error);
t.rollback();
});
})
.catch(error => {
reject(error);
t.rollback();
});
});
}
//Run transaction to addScheduledTransactionAttempts
return db.sequelize.transaction().then(function(t) {
let promiseArr = [];
var i = 0;
invoices.forEach(function(invoice) {
var schedulePaymentDate = moment(paymentDate);
if (invoice) {
let tryPayOnDate = schedulePaymentDate
.add(i, "month")
.format("YYYY-MM-DD");
promiseArr.push(
addScheduledTransactionAttempts(invoice, tryPayOnDate, t) //calling above function
);
i++;
}
});
//now execute promise all
Promise.all(promiseArr)
.then(function(result) {
t.commit();
return true;
})
.catch(function(err) {
t.rollback();
return false;
});
});
});
在上面的代码中我想改变
Promise.all(promiseArr)
这是在打电话
addScheduledTransactionAttempts
函数对简单的异步函数进行数据库查询,以使其更容易理解,而无需多个
.then
或 .then inside then
promise 。任何有关的帮助将不胜感激,
谢谢。
最佳答案
这很简单。 await
在调用返回 Promise 的方法时有效。您的所有 SDK 方法都已经返回了一个 promise,因此重构应该非常简单。这里有一些让你离开地面的东西:
const processInvoices = async currentLoggedInUser {
const invoices = await db.Invoice.findAll({
where: {
user_id: currentLoggedInUser,
status: {
$ne: 'paid',
},
},
});
if (yourOwnLogicForInvoicesObject) {
for (const invoice of invoices) {
const potentiallyFoundInvoice = await db.ScheduledTransactionAttempts.find({
where: {
invoice_id: invoice.id,
},
});
if (potentiallyFoundInvoice) {
await addScheduledTransactionAttempts(potentiallyFoundInvoice)
}
}
}
}
const addScheduledTransactionAttempts = async invoice => {
console.log('Do something with your invoice', invoice)
}
长话短说:将函数中的代码重构为更小的函数,并创建这些新函数
async
,就像我对 addScheduledTransactionAttempts
和 processInvoices
所做的一样更多关于 async/await
关于node.js - 如何使用 async await Node js 重构 promise 所有链并续写 ORM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57176453/