Enhancing the output of a promise by including additional data

Currently, I am utilizing a node library that facilitates simple HTTP requests and returns promises. This method works well for me as it allows multiple requests to be made simultaneously, which I can then gather later using Promise.all(). However, the challenge lies in the fact that each HTTP request only returns a string, whereas I also require additional identifying information about each request.

To address this issue, my approach involves extending the request promise chain to include the necessary information. Below is an example of how I am adding one such request to the array of promises:

var promises = [];
promises.push(new Promise(function(resolve, reject){
    ReqPromise('http://some.domain.com/getresult.php')
    .then(function(reqResult) {
        resolve({
            source: 'identifier',
            value: reqResult
        });
    });
}));

When this particular promise resolves, this is the output:

{
    source: 'identifier'
    value: 1.2.3.4
}

Do you think this method of tagging a promise result is optimal or is there perhaps a misunderstanding on my part regarding promises that eliminates the need for creating an additional promise as demonstrated above? It is worth noting that ReqPromise is from an external library, making it challenging to modify its behavior to accept and return extra parameters.

Answer №1

Big thanks to @Bergi for sharing the helpful link. I've put together this code, which is much more organized and easier to follow. I had attempted something similar in the past, but it seems I made an error because it was giving back undefined to Promise.all(). However, now everything is running smoothly without any additional promises needed.

promises.push(ReqPromise('http://some.domain.com/getresult.php').then(function(reqResult) {
    return {
        source: 'identifier',
        value: reqResult
    };
}));

Answer №2

Hello @dsl101, taking a step further from your answer, it can be quite beneficial to use the .map() method on an array of data in order to transform it into an array of promises. This way, you can easily link each item of data with its asynchronously-obtained result.

Let's consider a scenario where you have an array of URLs.

var data = ['http://path/0', 'http://path/1', 'http/path/2', ...];
var promises = data.map(function(url) {
    return ReqPromise(url).then(function(reqResult) {
        return {
            'source': url,
            'value': reqResult
        };
    });
});
Promise.all(promises).then(function(results) {
    // each result now contains a .value and corresponding .source (url) property
});

Answer №3

Thanks to the async/await syntax that was introduced in ES8, it is now possible to await a promise directly within an object literal.

This answer has been revised by @dsl101 to incorporate the async/await feature:

promises.push((async function() {
    return {
        source: 'identifier',
        value: await ReqPromise('http://some.domain.com/getresult.php')
    };
})());

Here is another example provided by @Roamer-1888:

var data = ['http://path/0', 'http://path/1', 'http://path/2', ...];
var promises = data.map(async function(url) {
    return {
        'source': url,
        'value': await ReqPromise(url)
    };
});
var results = await Promise.all(promises)

It is worth mentioning that functions can also be replaced with arrow functions for brevity.

Edit: Please note that when pushing promises into an array, the function must be called first to "transform" it into a promise. In the case of using .map, the function is automatically called so it is already a promise.

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 combine Ajax, JS, HTML, PHP, and MySQL in a single project?

I am looking to create a web application and wondering if I can integrate Ajax, JavaScript, HTML, PHP, and MySQL all together? ...

Storing Firebase credentials securely in Vue.js applications after deployment with environment variables (env_var)

I've been attempting to deploy my firebase&vue application, but I've encountered issues with adding firebase credentials to the environment variables. Here's the structure within vue.js: config ---- key.js ---- keys_dev.js ---- key ...

How to modify the content type in an Angular.js $http.delete request

When making a $http.delete request in my Angular app, I include a config object using the following approach: return $http.delete('projects/' + projectID + '/activityTypes', {data: [{id: 2}]}) This method attaches the values from my d ...

Issue with Framer Motion Modal: Animation presence fails to function

Currently, I am facing an issue with the exit animation of a modal created using framer motion. While the initial animation on opening the modal works perfectly fine, the exit animation fails to trigger and the modal disappears abruptly without any transit ...

The process of masking a video with alpha data from another video on canvas seems to be experiencing a

I have a unique setup on my page where I'm masking one video with another. Essentially, when the Play button is pressed, a second video slowly appears over the looping video in the background. This effect is achieved by using a black/white mask transf ...

Suspend operation to delay for ajax call within a websocket

Looking for a solution regarding a WebSocket that updates a messaged list when receiving a message. Currently using a fetch request to retrieve data from the server in order to populate the messaged list. However, facing an issue as the code needs to pau ...

Acquiring a fresh scope in Angular via a different component

In my project, I am developing an app using a component-based approach with Angular 1.5.5. As part of this development, I am utilizing d3js to create some elements with the class .floating-node. For each of these nodes, I am creating a new $scope and appe ...

Implementing key strokes in an HTML input field within a geckoWebBrowser

I am currently using the "geckoWebBrowser1" component to navigate to a URL that displays a login textbox with the ID: login-email Although I have successfully inserted "[email protected]" into the aforementioned textbox, it is essential to simulate k ...

Guide on utilizing AngularJS Filter service without HTML for Chrome extension development

Currently, I am attempting to utilize the filter service in AngularJS within my Chrome extension. However, I am unsure of how to properly obtain and inject it into my function. At this time, my code looks like: chrome.contextMenus.onClicked.addListener(fu ...

Experiencing difficulties with updating populated inputs that are connected to fetched data as they are not reflecting changes when modified

I am currently facing challenges with handling text fields in my web application. I need to retrieve data from the database, populate it in the appropriate fields, allow users to edit the information, and save any changes made. However, I have encountered ...

Trying to call an applet method using JavaScript will not be successful

When trying to invoke methods of a Java applet using JavaScript, I encounter an issue that requires the site to be added to trusted sites and security set to low in order for it to work properly. Otherwise, an error is thrown: Microsoft JScript runtime ...

Having difficulty changing the value of a Select element in AngularJS

Struggling to update the select value from AngularJs. Check out my code below: <select ng-model="family.grade" > <option ng-repeat="option in options" value='{{option.id}}'>{{option.text}}</option> </s ...

Expanding a JSON data structure into a list of items

In my Angular service script, I am fetching customer data from a MongoDB database using Django: getConsumersMongodb(): Observable<any> { return this.httpClient.get(`${this.baseMongodbApiUrl}`); } The returned dictionary looks like this: { &q ...

Are the orders of events maintained when emitted using an event emitter?

I have a simple query regarding the event emitter, which is crucial for my program's logic. Currently, I am utilizing an external library that triggers events that I'm listening to. These events consist of 'data' and 'error'. ...

Passport.js does not provide authentication for server-side asynchronous requests

Recently, I configured Passport.js with the local-strategy on my express server. Interestingly, when I am logged in and send an asynchronous request within NextJS's getInitialProps, it allows the GET request through client-side rendering but not serv ...

Utilizing Next.js to dynamically update data within a div element upon

I have a table set up to display data and I want to transfer the row data into a div when the user clicks on a table row: Currently, I can successfully get the data onclick: const handleClick = (rowData) => { console.log(rowData); } However, I am ...

Error message: Component is unable to access the $store property because it is undefined

After doing extensive research and reading numerous similar questions on various platforms, I am still unable to resolve my issue. I have a component containing a login form that triggers a method to dispatch a $store action for logging in the user via fi ...

Tips for converting Numbers or JSON to strings while exporting data to an Excel spreadsheet in React

I have been using react-html-table-to-excel to export my table to Excel. However, I have encountered a specific issue. I am unable to convert a Number to a string in one column. When I try to cast the Number to a string using <td>{String(post.did)} ...

How to download an Excel file (xlsx) using AngularJS and WebApi

I am currently working on a project that requires me to download a report in xlsx format. Despite successfully generating the report file on the server and receiving it on the client side, I am facing an issue where the file is not opening and is resulting ...

Ways to set a default image for an <img> tag

I am looking to set a default image to the img tag in case the user has not selected a profile picture for their account. Here is the current output: http://jsfiddle.net/LvsYc/2973/ Check out the default image here: This is the script being used: funct ...