多了解承诺

时间:2016-07-15 02:01:06

标签: javascript arrays promise sequelize.js

我正在努力使这项工作。我正在处理sequelize promisses,我想将查询的元素返回到视图,而是返回null。我知道它是因为promises是异步请求,并且在你调用它之后它不会立即返回结果,确定,但是如何返回值,将它放入数组而不是返回数组?

这是我到目前为止的代码。

router.post('/register', function(req, res, next) {
var sales = req.body.sales;
var person = req.body.personID;
var promisses = [];
var delivery = req.body.delivery;
for(var i =0;i<sales.length;i++){
    var product_id = sales[i].product_id;
    var amount = sales[i].amount;
    var price = sales[i].produto_price;

    var salePromisse = Sale.create({
      'product_id': product_id,
      'person_id': person,
      'amount': amount,
      'price': price,
      'total': amount*price
    });
    //i couldnt find a word which describes what movimentacao means...lets keep it.
    var movimentacao = Movimentacao.create({
      "tipo": 0,
      "id_product": product_id,
      "id_provider": "",
      "data": new Date(),
      "price": amount*price
    });
    promisses.push(salePromisse);
    promisses.push(movimentacPromisse);
}


Promise.all(promisses).then(function (promissesArray){
var name = "";
var suc = 0;
var total = 0;
var salesResult = [];
var salesObject = {};
if(!delivery){
  res.send({msg: "aaaaa"});
}else{
  promissesArray.forEach(function(pro){
    if(pro!==null && pro !== undefined){
      if(pro['$modelOptions'].tableName === undefined){
        Product.findById(pro.product_id).then(function (product){
          salesObject.product = product.name;
          salesObject.price= pro.price;
          salesObject.amount = pro.amount;
          salesObject.total = pro.total;
          total += salesObject.total;
          salesResult.push(salesObject);
          salesObject = {};
          return Person.findById(per);
        }).then(function (person) {
           name = person.name;
        });;
      }
    }        
  });
  //here is where i would like to return to the view salesResult and name.
  //res.render("folder/view", {sales: salesResult, person: name});
  console.log(salesResult);
}

});

});

嗯,promisses数组为我的每个模型都有CREATE实例,我正在创建它的几种类型。
我想在数据库上插入,检查解析的promise是否正在处理特定的表(字段modelOptions未定义,我已经调试过),查询所有其他结果,因为在promisses数组上我只有id,并且而不是放入数组才能返回视图,但在最后一行的console.log上,它返回null。如何改进代码以便能够完成我想要的所有操作而不是返回视图?

别担心,所有与模型相关的变量都在上面声明。

感谢。

0 个答案:

没有答案