我正在使用 Geocodio,它是基于回调的地理编码。我有一个对象数组,每个对象中都嵌套了一个餐厅对象。请参见下面的示例:
{
id: 0, title: "Half off all pizzas",
details:"Carry out only, all-day",
days: ["Monday", "Tuesday"],
restaurant: {
name: "Papa John's",
addressOne: "2937 Greenville Ave",
city: "Dallas",
state: "TX",
zip: 75206
}
}
我目前正在对对象数组进行映射,以将每家餐厅的地址传递到地理编码函数中。然后我想向该对象添加一个名为 location 的属性,该属性将包含地理编码的结果。但是,在函数的结果可以传递到对象之前返回元素。见下文:
generateCoordinates (req, res, next) {
var newDeals = deals.map((cur, ind, arr) => {
location = new Promise (function(resolve, reject) {
geocodio.get('geocode', {q: `${cur.restaurant.addressOne},
${cur.restaurant.city}, ${cur.restaurant.state},
${cur.restaurant.zip}`}, function(err, response) {
if (err) {
reject(err)
throw err;
}
else {
var result = JSON.parse(response);
let obj = result.results[0].location;
// console.log(obj);
resolve(obj)
}
}
)}).then((obj) => {
cur.location = obj;
console.log(cur)
return cur;
})
return cur;
// console.log(newDeals)
})
res.status(200).send(newDeals)
},
我很有可能在此处滥用了 Promise 构造函数。 .then 中的 console.log 显示每个元素都正确添加了 location 属性,但响应和 console.log(newDeals) 将值显示为“Promise”。
如何设置数组中每个元素的位置属性?
最佳答案
是的,除了调用 resolve
或 reject
之外,您不应该在异步回调中执行任何操作。特别是你不应该throw
!
return cur
并不完全有效,因为它发生在 promise 将被解析之前。您需要从 map
回调中返回 promise ,然后使用 Promise.all
等待数组中的所有 promise 。当最终完成时,您才可以发送响应。也不要忘记在发生错误时发送适当的响应。
generateCoordinates (req, res, next) {
var newDeals = deals.map((cur, ind, arr) =>
new Promise((resolve, reject) => {
geocodio.get('geocode', {
q: `${cur.restaurant.addressOne},
${cur.restaurant.city}, ${cur.restaurant.state},
${cur.restaurant.zip}`
}, (err, response) => {
if (err) reject(err);
else resolve(response);
});
}).then(response => {
var result = JSON.parse(response);
let obj = result.results[0].location;
cur.location = obj;
console.log(cur)
return cur;
})
);
Promise.all(newDeals).then(results => {
res.status(200).send(results);
}, err => {
res.status(500); // or whatever
console.error(err);
});
}
关于javascript - 使用 Promise 构造函数转换数组中的每个元素并将元素返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48771823/