Skip to content Skip to sidebar Skip to footer

Turning A Mongoose Seeding Script Into A Promise

I'm trying to wrap my head around promises trying to solve a scenario I find myself in a lot of times: seeding a MongoDB database. So I got the following script which I want to tur

Solution 1:

Please try to do it through new Promise and Promise.all

new Promise to create a new promise. The passed in function will receive functions resolve and reject as its arguments which can be called to seal the fate of the created promise.

Promise.all is useful for when you want to wait for more than one promise to complete.

var bookOps = [];

books.forEach(function (book) {
    bookOps.push(saveBookAsync(book));
});

Promise.all(bookOps).then(function() {
   bookshelfConn.close(function () {
      console.log('Mongoose connection closed!');
    });
});

functionsaveBookAsync(book) {
    returnnewPromise(function(resolve, reject) {
        newBook(book).save(function(err) {
            if (err)
                reject(err);
            elseresolve();
        })
    });
}

Post a Comment for "Turning A Mongoose Seeding Script Into A Promise"