无法将对象推入另一个对象,如何更改代码以与async/await一起使用? [英] Can't push object into another object, how can I change my code to work with async/await?

查看:44
本文介绍了无法将对象推入另一个对象,如何更改代码以与async/await一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在尝试使用api分页"时遇到问题,我需要将多个对象合并为一个.但是,我似乎无法弄清楚如何用Promise做到这一点,而且我不确定如何使用async/await来获得最佳结果.

I'm having issues trying to work with api "pagination", I need to merge multiple objects into one. However, I can't seem to figure out how to do this with promises and I'm not sure how to work with async/await to get the best results.

我有一个称为Selly的类,可与Selly API一起使用.

I have a class called selly, which works with the Selly API.

getAllProducts(page = 1) {
    return this.makeRequest('products', { page: page });
}
makeRequest(endpoint, params = {}) {
    return axios
        .get(`https://selly.gg/api/v2/${endpoint}`, {
            headers: {
                Authorization: `Basic ${this.genApiToken(this.apiKey, this.apiEmail)}`,
                'User-Agent': `username - localhost`,
            },
            params: params,
        })
        .catch((err) => {
            console.log(err);
        });
}

效果很好,直到我意识到我需要获取多个页面并将所有结果组合到一个对象中.这是我的尝试:

Which worked great, until I realized I need to fetch multiple pages and combine all of the results into a single object. Here's my attempt:

app.get('/api/products', (req, res) => {
    res.setHeader('Content-Type', 'application/json');
    selly.getAllProducts().then((request) => {
        const pages = request.headers['x-total-pages'];
        let products = request.data;
        if (pages > 1) {
            let i = 2;
            while (pages >= i) {
                selly.getAllProducts(i).then((nextPageRequest) => {
                    nextPageRequest.data.forEach((item) => {
                        products.push(item);
                    });
                });
                i++;
            }
        }
        res.send(JSON.stringify(products));
    });
});

我似乎无法将nextPageRequest推到products对象.显然是因为res.send在承诺selly.getAllProducts(i)完成之前运行.

I can't seem to push nextPageRequest to products object. Obviously because res.send runs before the promise selly.getAllProducts(i) is finished.

我知道,对此的最佳优化是使用async和await,但是我只是不了解它的基本概念,或者,至少我将如何重构代码以使用async和await.

I understand that the best optimization for this is using async and await, however I just can't get the basic concept of it, or well, at-least how would I refactor my code into using async and await.

我该如何工作?

推荐答案

您可以使整个app.get处理程序async,然后使await成为初始请求,以找出有多少页,然后使用for循环和selly.getAllProductsawait附加调用,将结果推入products数组.请确保try/catch,以便您可以处理错误:

You can make the whole app.get handler async, then await the inital request to figure out how many pages there are, then use a for loop and await additional calls of selly.getAllProducts, pushing the result to the products array. Make sure to try/catch so you can handle errors:

app.get('/api/products', async (req, res) => {
  res.setHeader('Content-Type', 'application/json');
  try {
    const request = await selly.getAllProducts();
    const pages = request.headers['x-total-pages'];
    const products = request.data;
    for (let i = 2; i <= pages; i++) {
      const { data } = await selly.getAllProducts(i);
      products.push(...data);
    }
    res.send(JSON.stringify(products));
  } catch(e) {
    // handle errors
  }
});

这篇关于无法将对象推入另一个对象,如何更改代码以与async/await一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆