Search code examples
bluebirdknex.js

Bluebird promise join is not running in sequence


I am using promise with knexjs, but why promise join is not run in sequence, rows got deleted after inserted:

exports.seed = function(knex, Promise) {
  return Promise.join(
    knex('states').del(),
    knex('states').insert([
    {
      'id': 1,
      'name': 'Georgia'
    },
    {
       'id': 2,
       'name': 'Tennessee'
    }
   ]);
  );
};

Solution

  • Join is for promises that run in parallel, not in sequence. "For coordinating multiple concurrent discrete promises." Since you want to delete before insert they are not concurrent.

    Promises are executed as soon as they are created so I think this is a case for a regular then:

    exports.seed = function(knex, Promise) {
      return knex('states').del()
        .then(function() {
          return knex('states').insert([
            {
              'id': 1,
              'name': 'Georgia'
            },
            {
               'id': 2,
               'name': 'Tennessee'
            }
         ]);
      );
    };
    

    Of if you like ES6 and having things line up:

    exports.seed = (knex) => {
      return B.resolve()
        .then(() => knex('states').del())
        .then(() => knex('states').insert([
          {
            'id': 1,
            'name': 'Georgia'
          },
          {
            'id': 2,
            'name': 'Tennessee'
          }
        ]));
    }