为什么这个promise.all不起作用?

时间:2016-03-10 11:24:13

标签: node.js mongodb bluebird

var Promise = require("bluebird");
var MongoDB = Promise.promisifyAll(require('mongodb'));
var MongoClient = MongoDB.MongoClient;
var database = "mongodb://localhost/test";

MongoClient.connect(database)
.then(function(db) {
  var c1 = db.collection('c1');
  var c2 = db.collection('c2');
  return Promise.all([
    c1.count().then(function(count) {
      if(count==0) {
        return c1.insertMany([{a:1},{a:2}]);
      }
      else {  // what should I write here? 
      }       //
    }),
    c2.count().then(function(count) {
      if(count==0) {
        return c2.insertMany([{a:1},{a:2}]);
      }
    })
  ]);
})
.catch(function(err) {
  console.log(err)
});

它只是挂在那里。

我应该在其他部分写什么?

if(count==0) {
        return c1.insertMany([{a:1},{a:2}]);
      }
      else {  // what should I write here? 
      }       //

1 个答案:

答案 0 :(得分:0)

我想db.collection()也会返回一个promise,所以你需要编写类似这样的东西

var Promise = require("bluebird");
var MongoDB = Promise.promisifyAll(require('mongodb'));
var MongoClient = MongoDB.MongoClient;
var database = "mongodb://localhost/test";

var insertIfEmpty = function(collection) {
  collection.count().then(function(count) {
    if(count==0) {
      return collection.insertMany([{a:1},{a:2}]);
    }
    else {  
      return Promise.resolve()
  });
}


MongoClient.connect(database)
.then(function(db) {
  var promisedCollections = [db.collection('c1'), db.collection('c2')]

  return Promise.all(promisedCollections).map(insertIfEmpty);
})
.catch(function(err) {
  console.log(err)
});

如果您需要一次填充一个集合,可以使用.each代替.map