将promise链中的值传递给处理程序

时间:2016-12-09 16:08:50

标签: javascript node.js

在promise链中传递值时遇到问题。我有一个与CustomerRepo对话的CustomerController

 var express = require('express')();
 var customerRepo = require('../repositories/customerRepo');

 var customerController = function () {
 var get = function (req, res) {
    if (typeof(req.query.offset) === 'undefined' ||        typeof(req.query.return) === 'undefined')
        res.status(422).send({'message': 'missing paging parameters'});

    req.query.offset === '' ? req.query.offset = 0 : req.query.offset;
    req.query.return === '' ? req.query.return = 50 : req.query.return;

    let getCustomers = customerRepo.getCustomers(req.query.offset, req.query.return);
    let getProfiles = customerRepo.getProfiles(customerList);
    let sendPayLoad= function (customerList) {
        console.log(customerList); /////  <===============
        res.send(customerList);
    }

    getCustomers
        .then(getProfiles)
        .then(sendPayLoad)
        .catch(function (err) {
            res.status(500).send(err);
        })
  }
  return {
     get: get
  }
}
module.exports = customerController;

CustomerRepo中的两个方法

    var getCustomers = function (offset, _return) {
    return new Promise(function (resolve, reject) {
    {
        var customers = [];
        var sql = 'sql here';
        SqlQuery(sql)
            .then(function (rows) {
                for (var i = 0; i < rows.length; i++) {
                    var customer = new Customer();
                    customer = rows[i];
                    customers.push(customer);
                }
                resolve(customers[0]);
            })
            .catch(function (err) {
                reject(err);
            })
    }
    });
}

var getProfiles = function (customers) {
    return new Promise(function (resolve, reject) {
    let ids = customers.map(function (item) {
        return item.CustomerId;
    });
    var customerList = [];
    let sql = 'sql here';
    SqlQuery(sql)
        .then(function (rows) {
            // do some processing to extract profile data from rows 
               and push to customerList so my profiles can be retrieved          like customers[0].Profiles
            console.log(customerList);/////  <===============
            resolve(customerList);
            return customerList;
        })
        .catch(function (err) {
            reject(err);
        })
    });
}

module.exports = {
    getCustomers: getCustomers,
    getProfiles: getProfiles
}
getProfiles中的

console.log(customerList)生成我正在寻找的所需json响应,如下所示

    [{ "CustomerId" : 123,
   "Name" : "myCustomer",
   .....
   Profiles[{
     "profile1" : "myProfile",
      .....
   }]
]

但控制器中的res.send(customerList)仅返回没有配置文件的客户。问题实际上是在承诺之间传递价值。

1 个答案:

答案 0 :(得分:0)

未定义sendPayload。您的函数名为send。它将数据传递给未定义的函数。这可能就是为什么你没有看到它。