为多个 POST 请求创建动态承诺链

问题描述 投票:0回答:1

我正在努力想出一个动态解决方案,我有一个项目数组,我需要为数组中的每个项目发送一个 POST 请求,但是在解决前一个承诺之前我不想发送下一个请求.

因此动态链接 .then() 方法,即发送第一个 POST 请求,在发送第二个 POST 请求之前等待该请求得到解决,在发送第三个 POST 请求之前等待第二个请求得到解决,等等

这是我的静态代码,我在其中发送 commandPayloads 数组中第一项的 POST 请求,然后在第一个项解决后发送第二项的 POST 请求。

const commandPayloads = await createInitialCommands(copiedCommands);

  commandPOSTFetch(commandPayloads[0], newResponseSetID).then(() => {
    commandPOSTFetch(commandPayloads[1], newResponseSetID);
  });

const commandPOSTFetch = async (command, newResponseSetID) => {
  const res = await fetch(`https://${someWebSite}/${appID}//${interactionID}/response/${newResponseSetID}/commands.json`,
    {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(command),
    }
  );
  const data = await res.json();
  return data;
};

如果数组中有 2 个项目,上面的示例就可以工作,但是如果我有超过 2 个项目怎么办?

如何根据数组中的项目数使此逻辑动态化,以便仅在解决前一个请求之后才按顺序发送 POST 请求?

javascript asynchronous fetch-api es6-promise
1个回答
0
投票

要根据

commandPayloads
数组中的项目数量实现 POST 请求的动态链接,您可以使用 Promises 的递归方法。以下是如何做到这一点的示例:


    const commandPayloads = await createInitialCommands(copiedCommands);
    
    // Function to send a POST request and return a Promise
    const commandPOSTFetch = async (command, newResponseSetID) => {
      const res = await fetch(`https://${someWebSite}/${appID}//${interactionID}/response/${newResponseSetID}/commands.json`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(command),
      });
      const data = await res.json();
      return data;
    };
    
    // Function to chain the POST requests sequentially
    const sendSequentialRequests = (payloads, index = 0) => {
      if (index < payloads.length) {
        return commandPOSTFetch(payloads[index], newResponseSetID)
          .then(() => sendSequentialRequests(payloads, index + 1));
      } else {
        // All requests have been sent
        return Promise.resolve();
      }
    };
    
    // Start the chain of requests
    sendSequentialRequests(commandPayloads)
      .then(() => {
        // All requests are completed
        console.log("All POST requests have been sent.");
      })
      .catch((error) => {
        console.error("Error:", error);
      });

此代码定义了一个

sendSequentialRequests
函数,该函数使用 Promises 以顺序方式一一发送 POST 请求。它首先发送第一个请求,当该请求得到解决时,它会使用下一个索引递归地调用自身,直到发送所有请求。最后的
.then()
.catch()
处理整个请求序列的完成或错误。

© www.soinside.com 2019 - 2024. All rights reserved.