首页 > 解决方案 > 那么为什么我不能从 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;
}

标签: javascriptobjectpromise

解决方案


这是常见的初学者问题,您试图获得结果数组,但您应该获得一系列承诺,然后全部解决

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
}

推荐阅读