gpt4 book ai didi

node.js - 如何在路由器中延迟响应?

转载 作者:太空宇宙 更新时间:2023-11-04 02:19:35 26 4
gpt4 key购买 nike

我想使用sequelize orm从多个表中收集数据。这是我的代码

var recs = [];

models.Data.findAll({
where: {
//exchange_id: req.params.exchangeId
exchange_id: 7
}
})
.then(function (data) {
var rec = {};

data.forEach(function (item, i) {
console.log('\n data id is ', data[i].id);

models.ExchangeTable.findOne({
data_id: data[i].id
}).then(function (exchangeTable) {
models.Country_Money.findOne({
id: exchangeTable.country_money_id
}).then(function (countryMoney) {
rec.countryMoneyId = countryMoney.id;
rec.data = data[i];
});
});
});

recs.push(rec);
res.json(recs);
});

输出为:

Executing (default): SELECT "id", "sell", "buy", "exchange_id", "createdAt", "up
datedAt" FROM "Data" AS "Data" WHERE "Data"."exchange_id" = 7;

data id is 185

data id is 186
Executing (default): SELECT "id", "data_id", "country_money_id", "createdAt", "u
pdatedAt" FROM "ExchangeTables" AS "ExchangeTable" LIMIT 1;
GET /ServiceProviders/Exchange/table/5 200 60.349 ms - 4
Executing (default): SELECT "id", "data_id", "country_money_id", "createdAt", "u
pdatedAt" FROM "ExchangeTables" AS "ExchangeTable" LIMIT 1;
Executing (default): SELECT "id", "Country_id", "Money_id" FROM "Country_Money"
AS "Country_Money" LIMIT 1;
Executing (default): SELECT "id", "Country_id", "Money_id" FROM "Country_Money"
AS "Country_Money" LIMIT 1;

我的问题是我不知道如何在循环 block 中使用 deferred,因为给 Country_Money 模型的 where 条件提供了 Data 模型中必须提供的预期值。

请告诉我,我该如何解决这个问题?

最佳答案

在使用 res#json 发送响应之前,您无需等待 forEach 中创建的 promise 完成。尽管数据库查找可能需要一些时间,但它们是异步执行的,因此在 forEach 之后执行代码不会等待其完成。为了让它们等待,我们可以用 forEach 将迭代器中的每个 promise 映射到一个 promise :

var promises = data.map(function (item, i) {
console.log('\n data id is ', data[i].id);

// We must return a value here
return models
.ExchangeTable
.findOne({data_id: data[i].id})
.then(function (exchangeTable) {

// Every promise we create must be returned so that
// its parent waits for it to resolve before giving
// control to the next `then`
return models
.Country_Money
.findOne({id: exchangeTable.country_money_id})
.then(function (countryMoney) {

// Return an object literal with the data we want
// instead of affecting an external store.
// This will be the final value for an iteration
// and available as a member of the array result of `Promise.all`
return {
countryMoneyId: countryMoney.id,
data: data[i]
};
});
});
});

这将产生一系列可以交给 Promise#all 的 promise 。 。最后,依赖于每个 Promise 的代码必须放在 Promise#all 之后的 then 内。

return Promise
.all(promises)
.then(function (recs) {
// Here we receive the final result of each
// promise returned within `data.map` as an array
res.json(recs);
});

使用这种方法,我们不再需要维护 var recs = [];var rec = {};。看看 Array.prototype.map 的目的和行为为什么会这样。

关于node.js - 如何在路由器中延迟响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34150392/

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