【发布时间】:2020-04-23 08:26:15
【问题描述】:
我有这个具有多个 Promise 的幂等函数,是我为 Google Cloud Functions 编写的。 我想启用重试,因为我使用的 API 非常不一致。这需要在需要重试时返回被拒绝的承诺。
因此,我尝试返回一个 promise.all([]) ,但是当其中一个承诺失败时,它不会终止/停止函数。然后它甚至进入promise.all().then()?只有当所有 4 个承诺都成功时才会发生这种情况。
谁能指出我正确的方向?我正在尝试的东西是否有意义?
exports.scheduleTask = functions
.firestore.document("tasks_schedule/{servicebonnummer}")
.onCreate((snap, context) => {
servicebonnummer = snap.data().data.servicebonnummer;
bondatum = snap.data().data.bondatum;
servicestatus = snap.data().data.servicestatus;
tijdstip = snap.data().data.tijdstip;
firestorePromise = null;
firestoreFinish = null;
cashPromise = null;
cashFinish = null;
//Firebase
//firestoreSchedule executes the required promise
//checkFinished points to a database where it checks a boolean for idempotency
//firestoreFinish writes to this database and sets the boolean to true when the promise is successful
if (!checkFinished("tasks_schedule", servicebonnummer, "firestore")) {
firestorePromise = scheduleFirestore(
servicebonnummer,
bondatum,
servicestatus,
tijdstip
)
.then(output => {
firestoreFinish = markFinished(
"tasks_schedule",
servicebonnummer,
"firestore"
);
return output;
})
.catch(error => {
console.error(
"scheduleFirestore - Error connecting to Firestore: ",
error
);
return error;
});
}
//SOAP API
//cashSchedule executes the required promise
//checkFinished points to a database where it checks a boolean for idempotency
//cashFinish writes to this database and sets the boolean to true when the promise is successful
if (!checkFinished("tasks_schedule", servicebonnummer, "cash")) {
cashPromise = scheduleCash(
servicebonnummer,
moment(bondatum),
servicestatus,
tijdstip
)
.then(result => {
if (result[0].response.code === "2") {
cashFinish = markFinished(
"tasks_schedule",
servicebonnummer,
"cash"
);
return result;
}
throw new Error("Validation error, response not successful");
})
.catch(error => {
console.error("scheduleCash - Error connecting to CASH API: ", error);
return error;
});
}
//CHECK PROMISES
return Promise.all([
firestorePromise,
firestoreFinish,
cashPromise,
cashFinish
])
.then(result => {
removeTask("tasks_schedule", servicebonnummer);
return result;
})
.catch(error => {
console.error("scheduleTask - Retry: ", error);
return error;
});
});
【问题讨论】:
-
From MDN: "
Promise.all()返回一个Promise,当所有作为 iterable 传递的 Promise 都已实现或当 iterable 不包含 Promise 时,它会根据原因拒绝。第一个被拒绝的承诺。”因此,如果有任何承诺失败,它应该拒绝(致电catch())。这不是发生在你身上吗? -
这里缺少的关键是
catch返回一个成功解决的承诺,如果你没有通过创建一个返回新的错误来传播另一个错误。
标签: javascript node.js promise google-cloud-functions idempotent