Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding extra data to result of a promise

I'm using a node library which allows simple http requests to be made and returns a promise - this is working nicely, as it allows several to be made in parallel, and I'm then collecting them later with Promise.all(). However, the http request simply returns a string, and I need to know some extra identifying information about each request. So I though one way to do this was to chain something off the request promise and add that information in. This is the code I've got so far showing one such request being added to the array of promises I'll collect later:

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

And this is what I get back for this promise when it resolves:

{
    source: 'identifier'
    value: 1.2.3.4
}

Is this the ideal way to 'tag' a promise result? Or is there something about promises I'm misunderstanding which means I don't need to create an extra promise as above? Note that ReqPromise is in an external library and so it's hard to make it take extra parameters and return them.

like image 350
dsl101 Avatar asked May 18 '16 11:05

dsl101


1 Answers

Thanks to @Bergi for the link. This is the code I've ended up with, which I agree is much cleaner. I had tried something like this before, but must have made some mistake, as it was returning undefined to Promise.all(). But now is working nicely without extra promises.

promises.push(ReqPromise('http://some.domain.com/getresult.php').then(function(reqResult) {
    return {
        source: 'identifier',
        value: reqResult
    };
}));
like image 160
dsl101 Avatar answered Sep 22 '22 19:09

dsl101