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

Why this promise.all does not work?

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)
});

它只是挂在那里。

else部分应该写什么?

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

我想 db.collection() returns 也是一个承诺,所以你需要写这样的东西

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