0

If my project uses Promise a lot, is it a good idea to resolve promises for all arguments when writing a function? For example,

function foo (arg1, arg2, arg3) {
    // do stuff with arg1, arg2, arg3
}

let pArg1 = getArg1Async();
let pArg2 = pArg1.then(calcArg2Async);
let pArg3 = getArg3Async();

let p = Promise.join(pArg1, pArg2, pArg3, foo);

becomes

function foo(pArg1, pArg2, pArg3) {
    return Promise.join(pArg1, pArg2, pArg3, function(arg1, arg2, arg3) {
        // do stuff with arg1, arg2, arg3
    });
}

let pArg1 = getArg1Async();
let pArg2 = pArg1.then(calcArg2Async);
let pArg3 = getArg3Async();

let p = foo(pArg1, pArg2, pArg3);
abcdabcd987
  • 2,043
  • 2
  • 23
  • 34
  • Why do you have `pArg1 = getArg1Async()` and `pArg2 = pArg1.then(…)`? A then-able can only resolve/reject once, so why are you keeping `pArg1` around? – royhowie Oct 03 '15 at 03:44
  • @royhowie Becase `foo` needs values of both `pArg1` and `pArg2`. See https://stackoverflow.com/questions/28250680/how-do-i-access-previous-promise-results-in-a-then-chain – abcdabcd987 Oct 03 '15 at 03:45
  • 1
    @royhowie And I don't think it has something to do with `bluebird`. `Promise.join` is simply a syntax sugar, which is the same as `Promise.all([p1,p2,p3]).then([v1,v2,v3]=>{...})`. So, I removed the `bluebird` tag. – abcdabcd987 Oct 03 '15 at 03:58
  • 2
    Sorry, but I really don't understand the point of your question. You've coded a function that accepts three promises as arguments. What are you trying to do with those promises in that function? It seems that the goal of that function depends upon what you should be doing with those promises. There is no abstract correct architectural choice here. The answer is that it depends upon the goal of the function that receives those three arguments. – jfriend00 Oct 03 '15 at 06:35

1 Answers1

1

This is often called "lifting" a method. It's a useful and known technique and you can easily write a helper that does it for you:

function lift(fn){
    return function(){
       return Promise.all.call(this, arguments).then(fn);
    }
}

Or in "Modern Node" and ignoring this:

const lift = fn => (...args) => Promise.all(args).then(fn)

Which would let you do:

var lifted = lift(myFn);
// fn will run when the promises resolve 
// and return a promise for the value.
var res = lifted(promise1, promise2); 
Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504