使用异步而不是多次等待(Javascript)

时间:2020-07-30 23:48:48

标签: javascript reactjs performance api async-await

我有以下API调用。 getA,getB和getC是进行的API调用。由于我使用await,所以这些是顺序调用。

如何使其异步并仅在所有调用完成后才返回结果。

handler: async function (request, h) {
                const headers = { headers: { “x-userId”: “sdsds” } };
                const getA = ( await getData("app/getA”)) || options.headers.STORES;
                const getB = ( await getData("app/getB”)) || [];
                const getC = ( await postData("app/getC”, { payload: {} }, headers)) || [];
                const result = {
                    status: "OK",
                    payload: {
                        stores: getA,
                        markets: getB,
                        groups: getC
                    }
                };
                return h.response(result);
            }

2 个答案:

答案 0 :(得分:0)

不确定这是否是您想要的...

使用async / await的IMO是执行此操作的好方法,因为您需要确保有效负载具有该数据,但是我可能是错的。

handler: function (request, h) {
    const headers = { headers: { 'x-userId': 'sdsds' } };
    const payload = {};

    getData('app/getA').then(data => {
        payload.stores = data;
    });

    getData('app/getB').then(data => {
        payload.markets = data;
    });

    getData('app/getC').then(data => {
        payload.groups = data;
    });

    const result = {
        status: "OK",
        payload,
    };
    return h.response(result);
}

答案 1 :(得分:0)

您也许可以在所需的三个值中进行一个Promise.all。 Promise.all接受一个Promise数组并返回一个已解析的响应数组。他们可以以任何顺序解决,但是整体承诺直到所有承诺都解决后才能解决。

handler: async function (request, h) {
  const headers = { headers: { “x-userId”: “sdsds” } };

  const requests = [
    getData("app/getA”),
    getData("app/getB”),
    postData("app/getC”, { payload: {} }, headers))
  ];

  const [getA, getB, getC] = await Promise.all(requests);

  const result = {
    status: "OK",
    payload: {
      stores: getA || options.headers.STORES,
      markets: getB || [],
      groups: getC || [],
    }
  };

  return h.response(result);
}

注意:对于Promise.all,如果有任何一个Promise。拒绝,则整个Promise.all将被拒绝。 Promise.allSettled决定所有诺言是否兑现或达成。

相关问题