I've encountered a situation where I have multiple functions that return promises, and I want to generalize them. As a result, I've structured them in the following way:
function checkWebpageForReference(data){
//code to check webpage for reference
}
function takeScreenshot(data){
//code to take screenshot of webpage
}
function uploadReferencePictureToS3(data){
//code to upload picture to S3
}
function saveNewReferenceToDb(data){
//code to save new Reference to database
}
function readFile(data){
//code to read file from file structure
}
function deleteFile(data){
//code to delete file from file structure
}
In each function, I resolve data because I anticipate having numerous similar functions that need to be chained together without specific order:
readfile(somedata)
.then(upload)
.then(delete)
.then(save)
//etc
This chaining method works well until I encounter situations requiring Promise.all:
Promise.all([
referenceTools.checkWebpageForReference(req.body),
referenceTools.takeScreenshot(req.body)
])
.then(function(results){
utils.readFile(results[1])
.then(referenceTools.uploadReferencePictureToS3)
.then(utils.deleteFile)
.then(referenceTools.saveNewReferenceToDb)
.then(function(data){
res.json(data.newReference);
})
.catch(function(err){
utils.errorHandler(err);
res.send("Internal error occurred. Please try again later.");
});
})
.catch(function(err){
utils.errorHandler(err);
res.send("Internal error occurred. Please try again later.");
});
My challenge arises when using Promise.all().then(upload)
due to the combined resolutions from both checkWebpageForReference
and takeScreenshot
. In essence, within readFile
, accessing data
fields becomes difficult as the resulting promise is an array like [data, data]
.
Is there a recommended pattern or approach I could follow to simplify this process while ensuring modularity and adequate data transmission between promises?