How to guarantee all requests are fulfilled asynchronously, and map the request url to the promise response in Node.js 10.x.x?

  fetch, javascript, node.js, promise

I have several GET Requests that need to be made, and due to a Timeout limitation, they have to be run asynchronously and I need to guarantee all run. Also, when the result returns, I need to know to which URL it is referred.

The first part I’ve managed to solve, but I’m unable to map to the correct url. Here is the code:

urls = ['https://example-a.com', 'https://example-b.com', 'https://example-c.com']

Promise.all(promises.map(p => fetch(p.url))).then(function(res){
    var blobPromises = [];

    /* HERE I WOULD LIKE TO KNOW WHICH URL'S REQUEST WAS RETURNED */
    
    for (var j = 0; j < urls.length - 1; j++) {
        blobPromises.push(res[j].text());
    }
    return Promise.all(blobPromises);
}).then(function(body){
    var output = {rawData: body)};
    callback(null, output);
}).catch(callback);

How can this mapping be done?

Source: Ask Javascript Questions

LEAVE A COMMENT