我和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 scrap 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 scrap the ${index.competitor}: `))
            }
          });
       })
    });
    return Promise.all(dataPromises); // resolve all
}

关于javascript - 那为什么我不能操纵从 promise 里面返回的对象呢?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57971456/

10-12 12:19
查看更多