簡體   English   中英

解決超時時在 Array.map 中創建的承諾

[英]Resolve promises created within Array.map on a timeout

我正在嘗試使用超時來解決一系列承諾,以避免 API 請求出現速率限制異常。 但是,我仍然達到了速率限制,因為超時似乎不起作用。

不太確定如何進行這項工作。

router.route("/").put(async (req, res) => {
  const { apiKey: access_token, course, assignments } = req.body;
  try {
    const returnedIds = [];
    const promises = await assignments.map((assignment) => {
      return axios({
        method: "PUT",
        url: `https://url.to.api/api/v1/courses/${course}/assignments/${assignment.id}`,
        params: {
          access_token,
        },
        data: {
          assignment: {
            points_possible: assignment.points_possible,
          },
        },
      });
    });
    const promiseResolution = function() {
      Promise.all([...promises]).then((values) => {
        values.forEach((_, index) => {
          returnedIds.push(assignments[index].id);
        });
        res.status(201).json({
          returnedIds,
        });
      });
    };
    setTimeout(promiseResolution, 5000);
  } catch (e) {
    res.status(401);
  }
});

如果你只是想在 API 調用之間放置一些時間,這應該做。

router.route("/").put(async (req, res) => {
    const { apiKey, course, assignments } = req.body;
    try {
        const returnedIds = [];
        for (const assignment of assignments) {
            returnedIds.push(await loadID(apiKey, course, assignment));
            await wait(5000);
        }
        res.status(201).json({ returnedIds })

    } catch (e) {
        res.status(401);
    }
});

function wait(duration) {
    return new Promise((resolve) => setTimeout(resolve, duration));
}

function loadID(apiKey, course, assignment) {
    // Makes the request, parses out the stuff you want from the response...
}

我會警告不要使用Promise.all ,因為您可能想在發出下一個請求之前檢查每個請求的結果。 例如,如果第三個請求受到速率限制,您可能不應該費心再提出請求。

這是因為Promise.all會立即觸發所有承諾,所以您的setTimeout只是為所有承諾設置超時,而不是個別 promise 。 您應該嘗試為每個 promise 進行延遲:

const promises = await assignments.map((assignment) => {
      // some delay function

      return axios({
        method: "PUT",
        url: `https://url.to.api/api/v1/courses/${course}/assignments/${assignment.id}`,
        params: {
          access_token,
        },
        data: {
          assignment: {
            points_possible: assignment.points_possible,
          },
        },
      });
    });

你可以試試這個:(它是 React,但你應該只關注 fetchData 函數)並查看日志: https://codesandbox.io/s/zen-feynman-ql833?file=/src/App.js

暫無
暫無

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

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