Wednesday, 31 May 2017

Using multiple requests with promise

I am trying to use request-promise module to check multiple web sites. If I use Promise.all as per design, promise returns with first reject. What is the proper way to execute multiple request tasks and wait all requests to finish whether they are fulfilled or rejected? I have come up with following two functions.

CheckSitesV1 returns exception due to one rejected promise. However CheckSitesV2 waits all promises to finish whether they are they are fulfilled or rejected. I will appreciate if you can comment whether the code I write makes sense. I am using NodeJS v7.9.0

const sitesArray = ['http://www.example.com','https://doesnt-really-exist.org','http://www.httpbin.org'];

async function CheckSitesV1() {
    let ps = [];
    for (let i = 0; i < sitesArray.length; i++) {
        let ops = {
            method: 'GET',
            uri:sitesArray[i],
        };
        const resp = await rp.get(ops);
        ps.push(resp);
    }
    return Promise.all(ps)
}

function CheckSitesV2() {
    let ps = [];
    for (let i = 0; i < sitesArray.length; i++) {
        let ops = {
            method: 'GET',
            uri:sitesArray[i],
        };
        ps.push(rp.get(ops));
    }
    return Promise.all(ps.map(p => p.catch(e => e)))
}

CheckSitesV1().then(function (result) {
    console.log(result);
}).catch(function (e) {
    console.log('Exception: ' + e);
});

CheckSitesV2().then(function (result) {
    console.log(result);
}).catch(function (e) {
    console.log('Exception: ' + e);
});



via Meanteacher

No comments:

Post a Comment