mardi 24 janvier 2017

Modular promises and Promise.all()

I have a bunch of functions that return promises that I want to make generalized, and so I write them like this:

function prf1(data){
    var promise = new Promise(function(resolve,reject){
        //some stuff here
        data.new_variable1 = 1;
        resolve(data);
    });
    return promise;
)};

function prf2(data){
    var promise = new Promise(function(resolve,reject){
        //some stuff here involving data.new_variable1 or something else
        data.new_variable2 = 2;
        resolve(data);
    });
    return promise;
)};

function prf3(data){
    var promise = new Promise(function(resolve,reject){
        //some stuff here involving data.new_variable2 or data.new_variable1 or something else
        data.new_variable3 = 3;
        resolve(data);
    });
    return promise;
)};

I resolve data in each function because I plan to have a lot of these types of functions, and I don't know the order they'll be called in while chaining:

prf1(somedata)
.then(prf3)
.then(prf5)
.then(prf2)
//etc

This works fine until I have to do Promise.all:

 Promise.all([
    prf1(somedata),
    prf2(somedata)
 ])
.then(prf3)
//etc

This gives me errors, because the new promise returned by Promise.all() is an object that contains both resolutions from prf1 and prf2. Essentially, in prf3, I can't access data.new_variable1 or data.new_variable2 because the resulting promise is [somedata, somedata].

Is there a pattern I can follow to help me achieve what I need to do? I need to make the promises modular providing them with as much data as possible.

Aucun commentaire:

Enregistrer un commentaire