Utilizing the power of modular promises with Promise.all()

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?

Answer №1

To iterate over them, utilize the .map() function as demonstrated below:

Promise.all(...)
  .then(data => Promise.all(data.map(upload)));

If you are working on the server side, I strongly suggest using Bluebird instead of native Promises. This allows you to simplify the process like so:

Promise.all(...)
  .map(upload);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to use HTML elements to trigger actions in order to display or conceal divs using JavaScript?

Beginner - I am currently working on a webpage using TinyMCE wysiwyg and I would like to implement a functionality where I can display or hide certain divs upon clicking a link/button. Unfortunately, due to the structure of the page, it seems that I ca ...

Creating dynamic fields for an ExtJS chart

Can chart axes be customized using setFields? I looked through the documentation for a method called setFields, but couldn't find one. While I was able to use setTitle on an axes, setting the field proved to be more challenging. I have a variable ca ...

The jQuery mouseout functionality seems to be malfunctioning and not responding as expected

I am currently developing a slider that displays details when the mouse hovers over the logo, and hides the details when the mouse moves away from the parent div. jQuery('.st_inner img').mouseover(function() { jQuery(this).parent().siblings( ...

What is the best way to synchronize the scrolling of a container element with scrollspy?

In my layout, I have multiple sections with a scrollbar that displays buttons using scrollspy. Everything is working perfectly except for one issue - when scrolling too far down, the scrollspy disappears off the page to the right. Is there a way to adjust ...

"Utilizing an exported constant from a TypeScript file in a JavaScript file: A step-by-step guide

I am facing an issue when trying to import a constant from a TypeScript file into a JavaScript file. I keep encountering the error Unexpected token, expected ,. This is how the constant looks in the ts file: export const articleQuery = (slug: string, cate ...

When the value is removed, it does not revert back to the initial filtered choices

After clearing the input, I want to display all the original li's again. The issue is that even though .value = '' clears the input, the filter remains active. I could really use some help with this as it's starting to get on my nerves ...

Determine Checkout Total with Laravel 5.2 Based on Radio Button Selections

Currently, I am developing an e-commerce platform using Laravel 5.2. At the moment, I am able to add products to my shopping cart, which is stored in a session. Once I am ready to proceed, I can view my shopping cart and upon confirmation, I am directed t ...

Chrome's keyup event restricts the use of arrow keys in text fields

Could you please test this on Google Chrome browser: jQuery('#tien_cong').keyup(function(e) { jQuery(this).val(jQuery(this).val().replace(".", ",")); var sum = 0; var tien_cong = jQuery('#tien_cong').val(); tien_cong = tien_ ...

What is the best method for starting a string using the symbol '~'?

Hello everyone! I have a task that requires me to add a special feature. The user needs to enter something in a field, and if it starts with the tilde (~), all subsequent entries should be enclosed in a frame within the same field or displayed in a list ...

Is there a way to include an image in a serialized file?

What is the method to include image_form into form in Django? form - form.serialize() image_form - image $('#id_submit').click(function(e) { e.preventDefault(); var form = $('form').serialize(); image_form = $("#id_image")[0].f ...

Is it possible to maintain the scroll position of a PrimeNG table when updating the data?

I've encountered a challenge while working on a project involving PrimeNG 12 tables with Angular 12. The issue lies in Angular's change detection mechanism and updating table data, specifically in preventing a PrimeNG p-table from scrolling back ...

Fast updates in Mongo/Mongoose can lead to unintended data loss

Recently delving into mongo/mongoose, I encountered a bug when updating a collection. Within my nodejs code: User .findByIdAndUpdate({ _id: id }, { $set: params }) .select('-password') .exec(function (error, user) { return res. ...

Guide on utilizing async/await in .ts files (Encountering error message: "async functions can only be used when targeting ECMAScript 6 or above")

Initially, my project consisted of only app.js using ExpressJS as the main file with numerous lines of code. My development manager instructed me to refactor the code and move some functions into a separate .ts file (transition from JavaScript to TypeScrip ...

How is it possible that my array becomes reversed without any intervention on my part?

As I work on developing a website, I encountered a puzzling issue with the calculations inside the router. Despite initializing the array tomato with the desired values, it seems that the values get reversed just before rendering the page. Here is the code ...

Troubleshooting: Issue with Firebase callable function execution

In my index.js file, I have the following code snippet: const firebase = require("firebase"); const functions = require('firebase-functions'); // Firebase Setup const admin = require('firebase-admin'); const serviceAccount = require(&a ...

Locate the unique identifier of the window responsible for triggering alerts

Can anyone provide a solution for identifying the ID of the Internet Explorer window that triggers alert boxes? I suspect it is related to the document or window itself. This can be achieved using basic HTML or jQuery code. I attempted the following appr ...

Passing an object in an ajax call to a function: a comprehensive guide

@model IEnumerable<HitecPoint.BlackBox.Models.SMSReportModal> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"> </script> <script type="text/javascript"> var MyAppUrlSettin ...

"Troubleshooting vertical tab inconsistencies in Jquery: addressing unexpected gaps and alignment

After spending a considerable amount of time on this, I'm still struggling to make it work properly. The main issue is the gap between the tabs and the content area. I've tried adjusting the positioning, but it ends up affecting the overall layo ...

I seem to be having some trouble with localStorage. Can anyone shed some light on why this might be

I'm having trouble with the code below and need some assistance to achieve the desired result. HTML: Name: <input type="text" id="name" name="name"></input> <button id="send" type=&qu ...

Positioning a Material UI Menu item underneath its parent element using CSS styling

I have created a Material UI dialog that features some text and an Icon with a dropdown menu option. You can check out the demo here: https://codesandbox.io/s/prod-rain-1rwhf?file=/src/App.js My goal is to properly position the Menu component so that it a ...