0

Trying to use the Q promises library with couchDB and Nano. I have the following code and the messages are displayed in the console but the database is not created.

var nano = require('nano')('http://localhost:5984');
var Q = require('q');

var deleteDB = function(database) {
    console.log('deleteDB');
    var deferred = Q.defer();
    nano.db.destroy('alice', deferred.resolve);
    return deferred.promise;
};

var createDB = function(database) {
    console.log('createDB');
    var deferred = Q.defer();
    nano.db.create('alice', deferred.resolve);
    return deferred.promise;
}

deleteDB('promises').then(createDB('promises'));

Does anyone know why this does not work?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Mark Tyers
  • 2,961
  • 4
  • 29
  • 52

1 Answers1

1

One issue is that then() takes a function as an argument that is executed when the promise is resolved. Your code will execute createDB immediately after deleteDB and pass the resulting promise to then().

Another issue is that you aren't waiting for the promise returned by createDB to resolve.

So I think you want something like:

deleteDB('promises')
  .then(function () { return createDB('promises'); })
  .then(function () { console.log('All finished'); });

or if you change createDB so that it doesn't take an argument you can do

deleteDB('promises')
  .then(createDB)
  .then(function () { console.log('All finished'); });

Note the lack of () after createDB.

David Norman
  • 19,396
  • 12
  • 64
  • 54