【问题标题】:Conditionally create new entries using promises in Waterline (Sails.js)在 Waterline (Sails.js) 中使用 Promise 有条件地创建新条目
【发布时间】:2016-01-25 09:30:00
【问题描述】:

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

我无法使用 bluebird 承诺(使用 .all 或 .map)来做到这一点。我可以通过返回 Product.create(products[0]) 创建一个项目。我无法理解它,我对 promises 不熟悉。

这是我的sails.js 项目的引导文件,但这个问题是关于如何使用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.");
  });

【问题讨论】:

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


    【解决方案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.");
      });
    

    【讨论】:

      猜你喜欢
      • 2013-12-21
      • 2015-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多