0

I'm really new to Q js library.

I need to write a prepare function that may return value momentarily or may need to wait for promise:

var prepare = function() {
    var result = {};
    result.aaa = 1;

    if (something) {
        callToFunction().then(function () {
            result.bbb = 2
        })
    }

    if (something2) {
        callToFunction().then(function () {
            result.ccc = 2
        })
    }


    // here I have code to define other properties
    // in sync (like `aaa`) or async (like `bbb`) manner



    return result; //I need to return promise here
}

prepare().then(function(result) {use result....})

can someone fix prepare function so I can always safely use prepare().then

someone may think it is related to How to maintain a promise-like API in this case?

but it is not. Function is responsible to define result object.

  • first: define aaa property
  • second: in some cases function will define bbb property
  • third: define other properties in sync (like aaa) or async (like bbb) manner
Community
  • 1
  • 1
Cherven
  • 1,101
  • 3
  • 17
  • 26
  • 1
    How is your case different than the linked question? It seems to be just `if (something) return callToFunction().then(function() { …; return result; }); else return Q.resolve(result);` – Bergi Feb 25 '16 at 04:35
  • hm... I think I'm starting to understand you. Then how would you write function if I also have to define ccc asynchronously? So code will start executing definition of bbb and ccc in parallel. – Cherven Feb 25 '16 at 04:39
  • 1
    or maybe [Javascript - if with asynchronous case](http://stackoverflow.com/q/29802311/1048572) is a better duplicate? – Bergi Feb 25 '16 at 04:39
  • Then how would you write function if I also have to define ccc asynchronously? So code will start executing definitions of bbb and ccc in parallel. – Cherven Feb 25 '16 at 04:41
  • 1
    For that case, use [`Promise.all`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all) (or `Q.all`, of course) to gather results from multiple promises, then put them together in your object – Bergi Feb 25 '16 at 04:43
  • thanks that helps !!! – Cherven Feb 25 '16 at 16:09

0 Answers0