使用 Waterline 中的承诺有条件地创建新条目 (Sails.js)

Conditionally create new entries using promises in Waterline (Sails.js)

我有一个 "products" 的数组。 如果数据库为空,我想将这些产品保存到数据库中,当所有数据库操作完成时,我想显示一条消息。

我无法使用 bluebird promises(使用 .all 或 .map)做到这一点。我能够通过返回 Product.create(products[0]) 来创建一个项目。我无法理解它,我是新手。

这是我的 sails.js 项目的 bootstrap 文件,但这个问题是关于如何使用 bluebird promises 的。我如何设法等待多个异步任务(创建 3 个产品)完成然后继续?

  products = [
    {
      barcode: 'ABC',
      description: 'seed1',
      price: 1
    },
    {
      barcode: 'DEF',
      description: 'seed2',
      price: 2
    },
    {
      barcode: 'GHI',
      description: 'seed3',
      price: 3
    }
  ];


  Product.count()
  .then(function(numProducts) {
    if (numProducts > 0) {
      // if database is not empty, do nothing
      console.log('Number of product records in db: ', numProducts);
    } else {
      // if database is empty, create seed data
      console.log('There are no product records in db.');

      // ???
      return Promise.map(function(product){
        return Product.create(product);
      });
    }
  })
  .then(function(input) {
    // q2) Also here how can decide to show proper message
    //console.log("No seed products created (no need, db already populated).");
    // vs
    console.log("Seed products created.");
  })
  .catch(function(err) {
    console.log("ERROR: Failed to create seed data.");
  });

想通了...

  products = [
    {
      barcode: 'ABC',
      description: 'seed1',
      price: 1
    },
    {
      barcode: 'DEF',
      description: 'seed2',
      price: 2
    },
    {
      barcode: 'GHI',
      description: 'seed3',
      price: 3
    }
  ];


  Product.count()
  .then(function(numProducts) {
    //if (numProducts > 0) {
    if(false) {
      // if database is not empty, do nothing
      console.log('Number of product records in db: ', numProducts);
      return [];
    } else {
      // if database is empty, create seed data
      console.log('There are no product records in db.');
      return products;
    }
  })
  .map(function(product){
    console.log("Product created: ", product);
    return Product.create(product);
  })
  .then(function(input) {
    console.log("Seed production complete.");
  })
  .catch(function(err) {
    console.log("ERROR: Failed to create seed data.");
  });