userMod2 userMod2 - 4 years ago 69
Javascript Question

Putting Togther Q Promises

I'm learning about JS promises and have made some progress in my understanding of things, however unsure how to bring it together with

return
and using
Q.all


So say I have a function: (
getParentsForLocation
returns a promise)

function doBusiness() {

return Q.all(
locations.map(function(item, currentIndex) {
return getParentsForLocation(item.id)
.then(function(res) {
return checkParent(res, currentIndex)
}

});
}))
.then(_.uniq(locations))
}


Then following this i.e. after that map has gone through all elements in the
locations
array, I want to run something like underscore's
uniq
function:
_.uniq(someArrayIHave);



  1. Do i need to place this in a
    Q.all([])
    ? \

  2. If so, would it run each method in that array sequentially?

  3. I presume there is something I'd need to do with that
    doBusiness()
    function, e.g. return some promise, but unsure how that would look?



Any help appreciated.

Many Thanks.

Answer Source

Do i need to place this in a Q.all(…)?

Yes. Your map() call should get you an array of promises.

If so, would it run each method in that array sequentially?

No. Or at least, we don't know, they could do anything on the inside.

I presume there is something I'd need to do with that doBusiness() function, e.g. return some promise

Yes. From my promise rules of thumb: If a function does something asynchronous, it must return a promise. This is also true for your two callback functions.

How would that look?

function doBusiness() {
    return Q.all(locations.map(function(item, currentIndex) {
//  ^^^^^^ ^^^^^^
        return getParentsForLocation(item.id)
//      ^^^^^^
        .then(function(res) {
            return updateDB(res, currentIndex);
//          ^^^^^^
        });
    }));
//    ^
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download