javascript - 那么为什么我不能从 promise 内部操作返回的对象呢?
问题描述
我有并且承诺返回一个对象,我想循环遍历它以按价格排序,但我无法操纵返回的对象,我不知道为什么。
如果我只是console.log
像在第二个 console.log 上那样显示结果,但如果我做任何我在网络上创建的事情,它们会返回空数组。
这是我的代码:
getPrices().then(res => {
console.log(typeof res);
// console -> object
console.log('result', res);
// console -> [] {0: {price: "12.80", competitor: "competitor 1")...} length: 7 __proto__: Array(0)
console.log('stringfy', JSON.stringify(res));
// console -> stringfy []
console.log('array from', Array.from(res));
// console -> [] length: 0 __proto__: Array(0)
console.log('object keys', Object.keys(res));
// console -> [] length: 0 __proto__: Array(0)
});
我也尝试过使用Object.entries
和使用map
直接res
将此对象转换为数组并使用 .sort 或 .map 的正确方法是什么?
这是我的 gitPrice 函数:
export const getPrices = async () => {
const prices = [];
data.map(index => {
request(index.link, (error, response, html) => {
if (!error && response.statusCode == 200) {
let che, price, newItem;
che = cheerio.load(html);
price = (index.selector.includes("itemprop")) ? che(index.selector).attr('content') : che(index.selector).text();
newItem = {
"price": price,
"competitor": index.competitor
};
prices.push(newItem);
} else {
console.error(`ERROR ${response.statusCode}: Was not possible to scrape the ${index.competitor}: `)
}
});
});
return prices;
}
解决方案
这是常见的初学者问题,您试图获得结果数组,但您应该获得一系列承诺,然后全部解决
export const getPrices = () => {
const prices = [];
const dataPromises = data.map(index => { // this contains array of promises
return new Promise((resolve, reject) => {
request(index.link, (error, response, html) => {
if (!error && response.statusCode == 200) {
let che, price, newItem;
che = cheerio.load(html);
price = (index.selector.includes("itemprop")) ? che(index.selector).attr('content') : che(index.selector).text();
newItem = {
"price": price,
"competitor": index.competitor
};
resolve(newItem); // resolve the value
} else {
reject(new Error(`ERROR ${response.statusCode}: Was not possible to scrape the ${index.competitor}: `))
}
});
})
});
return Promise.all(dataPromises); // resolve all
}
推荐阅读
- java - 通过 apache.commons.io.FileUtils deleteDirectory 删除的文件去哪里了?
- python - 如果我们将 wkhtmltopdf 用于 pdfkit,我们如何在 aws 上部署 django 应用程序?
- python - pyTelegramBotAPI:机器人在 Heroku 上大约 1 小时后停止运行
- node.js - 在 nodejs 中访问 oData
- javascript - 我正在使用 window.fetch 下载文件,但在服务器上生成错误文件而不是在本地
- html - 模态弹出窗口未打开
- c# - sqlcmd 在 MSI 安装程序项目上不返回任何值,而它通常返回安装程序类之外的值
- dotnetnuke - DNN 升级 - Portal.css 未加载
- here-api - 在发送超过 250 个航点到 calculateroute.json 时获得 414 Request-URI Too Large
- json - 从 SectionList 中选择项目并将其与 Redux 状态同步的最佳方式/模式?(详情见正文)