gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 05:14:43 26 4
gpt4 key购买 nike

在 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",
.....
}]
]

但是我在 Controller 中的 res.send(customerList) 仅返回没有配置文件的客户。问题本质上是在 Promise 之间传递值。

最佳答案

sendPayload 未定义。您的函数名为 send。它将数据传递给未定义的函数。这可能就是您看不到它的原因。

关于javascript - 将 promise 链中的值传递给处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41064462/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com