KateYoak
KateYoak

Reputation: 1731

Waiting for promises - code hangs

I am using Javascript Promises for the first time and ran into something I don't understand.

What I am trying to do is create a validation phase which runs around and checks things - eventually waiting for all promises to resolve.

To do this, I create a validation promise:

 validate = function(data) {
     var p = new Promise(function(resolve, reject)){

Here I define a promises array for all the different things I will be doing:

         var all_promises = Array();

Now do things like this Sequelize call while adding promises into this array (Sequelize returns promises):

         all_promises.push(resBooking);
         resBooking.count(...).then(...).catch(...);

I have logging statements that demonstrate we got through then and everything is dandy. Now all I need to do is wait!

        Promise.all(all_promises).then(function(){
            p.resolve();
        });

But this silly thing hangs - it waits for something to complete. No CPU usage. What am I doing wrong?

Upvotes: 0

Views: 3397

Answers (1)

user663031
user663031

Reputation:

What you want is

validate = function(data) {
    var p = new Promise(function(resolve, reject)){
        var all_promises = Array();
        all_promises.push(resBooking);
        resBooking.count(...).then(...).catch(...);

        Promise.all(all_promises).then(resolve);
    });
    return p;
};

In other words, call resolve, not p.resolve(). p.resolve will generate a run-time error (p doesn't exist), which will be "swallowed" by the promise constructor and cause it to fail. However, you won't even be able to see that rejected promise from the outside, since you are also not returning it from the function.

However, although this code should work now, you are still committing the "promise constructor anti-pattern". You don't need to construct a new promise when you already have one in the form of the Promise.all. So you can just write

validate = function(data) {
    var all_promises = Array();
    all_promises.push(resBooking);
    resBooking.count(...).then(...).catch(...);
    return Promise.all(all_promises);
};

I am not sure the above is exactly what you want, though. I don't know what resBooking is, or resBooking.count. In any case, you will be waiting on the resBooking promise, rather than the result of the then and catch you are hanging off it. Depending on what you're trying to accomplish, you might want

validate = function(data) {
    var all_promises = Array();
    all_promises.push(resBooking.count(...).then(...).catch(...));
    return Promise.all(all_promises);
};

Upvotes: 5

Related Questions