我正在编写一个具有以下流程的软件:
Promise.resolve(updateMongoStatus)
.then(unzipFilesFromS3)
.then(phase4) //example
.then(phase5) //example
.then(processSomething)
.catch(saveErrorToMongo)
我想知道是否可以将数据从第一个函数传递到最后一个函数,例如:
function updateMongoStatus() {
// do something here that updates Mongo and get status of some document
return { status }
}
function unzipFilesFromS3({ status }) {
// do something here to unzip files from s3
return { status, files }
}
function phase4({ status, files }) {
// etc
}
直到processSomething
最终被调用:
function processSomething({ parameterFromOutputOfUpdateMongoStatus, parameterFromPhase4, parameterFromPhase5 }) {
// Do something here
}
这样可以吗?像这样传递数据?
谢谢。
最佳答案
是的!这完全没问题,对于某些人来说,这是通过 Promise 链传递数据的首选方式(因为它不涉及 Promise block 范围之外的任何全局变量/变量)。
就您而言,由于您希望在最后一个 promise 中获得 Phase4、Phase5 和 mongo 状态,因此您可以这样做:
Promise
.resolve(mongoStatus)
.then((mongoResult) => {
return unzipFilesFromS3().then(s3Result => {
return [s3Result, mongoResult];
});
})
.then(([ s3Result, mongoResult ]) => {
return Promise.all([
mongoResult,
s3Result,
phase4(mongoResult, s3Result)
]);
})
// repeat with phase5
.then(([ mongoResult, s3Result, phase4Result /* phase5, etc */ ]) => {
// etc
})
.catch(err => {});
关于javascript - 使用 Promises 执行流程,将一个函数的输出作为下一个函数的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49270355/