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

时间:2016-01-25 09:30:00

标签: node.js promise sails.js waterline bluebird

我有一系列"产品"。 如果数据库为空,我想将这些产品保存到数据库,并且当所有数据库操作完成后我想显示一条消息。

我无法使用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.");
  });

1 个答案:

答案 0 :(得分:1)

想出来......

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