Http and Promise.all to do parallel request

nativescriptcore

#1

I am need to make a parallel http request by passing an array of http request to a Promise.all. I have looked around and have seen some pure node js examples that uses callbacks with other plugins For example this https://stackoverflow.com/questions/36074860/making-multiple-http-calls-and-consolidating-results-with-promises. I am not sure if these would work for nativescript seeing that its hhtp module is implemented a little different. Does anyone have an example of a parallel http request call or could point me in the right direction? I am using simple Javascript not Typescript or Angular.


#2

Hey @jessiPP
I did a quick research for you and put up a code sample :slight_smile:

You can use "Bluebird"
Install by running npm i bluebird in your project directory.

And you can use it something like this

exports.onNavigatingTo = function(args) {
    var page = args.object;

    var promises = [];
    for (let i = 0; i < 5; ++i) {
        promises.push(getPromise(i));
    }
    Promise.all(promises)
        .then(values => {
            console.log("all the promises were resolved!");
            for (let val of values) {
                console.log(val);
            }
        })
        .catch(e => {
            console.log("error: ", e);
        });
};

function getPromise(i) {
    var Promise = require("bluebird");
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve("Parallel Promise Number: " + i);
        }, 1000);
    });
}

And that prints

JS: all the promises were resolved!
JS: Parallel Promise Number: 0
JS: Parallel Promise Number: 1
JS: Parallel Promise Number: 2
JS: Parallel Promise Number: 3
JS: Parallel Promise Number: 4

Cheers! Happy NativeScripting


#3

Thank you so very much for your time and effort. I like this solution. I was trying to using this https://stackoverflow.com/questions/31761648/async-parallel-http-request but I rather the Promise approach that you offer.


#4

@jessiPP
Glad that I could help,
Like in one of the answers in the SO link you sent,
You can couple this technique with async/await and make it even more convenient.