簡體   English   中英

使用 async 而不是多個 await (Javascript)

[英]Use async instead of multiple await (Javascript)

我有以下 API 調用。 getA、getB 和 getC 是正在進行的 API 調用。 由於我使用等待,這些是順序調用。

我如何使其異步並僅在所有調用完成后才返回結果。

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);
            }

不確定這是否是您要找的...

IMO 使用 async/await 是一種很好的方法,因為您需要確保有效負載具有該數據,但我可能錯了。

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);
}

您可能可以執行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在所有承諾都已履行或拒絕時解決。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM