meanrims
meanrims

Reputation: 65

Promise problems - .then() not getting called?

I have two Sequelize queries that I need to run in a specific order, the first creates a model and the second creates multiple models from an array. It works in that it inserts obj1 first and then the array of transactions, however the final 'then()' doesn't seem to get called... What am I doing wrong?

var fn = function addTransaction(transaction) {
     return new Promise(function() {
          return Transaction.create(transaction, { fields: [ 'Id', 'Name' ]});
     }
};

var transactions = [...]; //array of transaction objects

Model1.create(obj1, { fields: [ 'Id', 'Name' ,'Description' ]}).then(function() {

    var actions = transactions.map(fn);
    var results = Promise.all(actions).then(function(data) {
        return Promise.all(data.map(fn));
    });
    results.then(function() {
        console.log("Done?"); //not getting called
    });

}).catch(function(err) {
    console.log(err);
});

Upvotes: 0

Views: 1886

Answers (2)

jfriend00
jfriend00

Reputation: 707198

addTransaction() is never going to resolve the promise it creates. You create an outer promise and return it, but never resolve it. You would at least have to declare a resolve argument to that callback and then call resolve() somewhere.

But, if Transaction.create() already returns a promise, then you can change addTransaction() to this:

var fn = function addTransaction(transaction) {
     return Transaction.create(transaction, { fields: [ 'Id', 'Name' ]});
};

It's also unclear why you're using the same fn to process both the transactions array and the data array that results from each of those transactions. That seems a little odd from a logic point of view. Are you sure that's the correct way to write your code? For us to help you with the design of that part of the code, you'd have to explain more about what you're trying to accomplish by calling fn on both the first array of transactions and then again on the results from that.

Upvotes: 2

Sanketh Katta
Sanketh Katta

Reputation: 6311

I'm not sure if this will solve your problem exactly, but I think you are missing a return:

...
return results.then(function() {
    console.log("Done?"); //not getting called
});
...

Without it the Model1.create promise would resolve before the results finish.

Upvotes: 0

Related Questions