gpt4 book ai didi

Create a dynamic promise chain for multiple POST requests(为多个POST请求创建动态承诺链)

转载 作者:bug小助手 更新时间:2023-10-28 10:02:12 27 4
gpt4 key购买 nike



I'm struggling to come up with a dynamic solution, I have an array of items, I need to send a POST request for each item in the array, however I do not want to send the next request until the previous promise is resolved.

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


So dynamically chaining .then() methods, i.e. send the first POST request, wait for that to get resolved before sending the second POST request, wait for second to get resolved before sending third POST request, etc.

因此动态链接.Then()方法,即发送第一个POST请求,在发送第二个POST请求之前等待解析,在发送第三个POST请求之前等待解析Second,依此类推。


Here is my static code, where I send a POST request for the first item in the commandPayloads array, then send a POST request for the second item after the first is resolved.

下面是我的静态代码,我在其中为命令有效负载数组中的第一个项目发送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;
};

the example above is working if there are 2 items in the array, but what if I have more than 2?

如果数组中有2个项目,上面的示例是有效的,但如果我有2个以上的项目怎么办?


How can I make this logic dynamic, based off the number of items in the array, so the POST requests are sent in sequential order, only after the previous is resolved?

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


*Update with For Loop

*使用For循环进行更新


  commandPayloads.forEach(async (command, i) => {
const data = await commandPOSTFetch(command, newResponseSetID)
console.log('in loop', data);
});

更多回答

return commandPOSTFetch(commandPayloads[1...

返回命令POSTFetch(命令有效负载[1...

Don't mix .then() code with async/await. Write a simple loop and await each fetch in the loop.

不要将.Then()代码与Async/AWait混合在一起。编写一个简单的循环,并等待循环中的每个FETCH。

@Pointy hmm, maybe I'm missing something but I tried a for loop and used await for every fetch, they still seem to be resolving out of order, i.e. sometimes the first POST request is the third element in the returned array.

@Pointty嗯,也许我遗漏了什么,但我尝试了for循环,并在每次FETCH时使用等待,它们似乎仍在无序解析,即有时第一个POST请求是返回的数组中的第三个元素。

You're passing an async function to .forEach(). That method ignores the return value. I said in my comment above "a simple loop", by which I meant a simple for loop, not .forEach().

您正在将一个异步函数传递给.forEach()。该方法忽略返回值。我在上面的评论中提到了“简单循环”,我指的是简单的for循环,而不是.forEach()。

Answer added, this is a frequent question but yours is pretty well worded so hopefully it will be useful to other people.

回答补充说,这是一个常见的问题,但你的措辞很好,所以希望它能对其他人有用。

优秀答案推荐

Just for the record, it turns out that the simplest thing to do (and, really, given the "wait until one thing finishes before doing the next thing" requirement, almost the only way to do it) is to use a good old-fashioned for loop:

根据记录,最简单的事情就是使用一个好的老式for循环(实际上,考虑到“等到一件事情完成后再做下一件事情”的要求,几乎是唯一的方法):


let listOfThings = whatever;
for (let i = 0; i < listOfThings.length; ++i)
const asyncResult = await somefunc(listOfThings[i]);
// ...
}

The reason a for loop is better in this case than .forEach() or even .map() is that in an async function, those await expressions really will wait until each Promise is satisfied before proceeding to the next iteration. (Obviously in real code you'd deal with exceptions etc.)

在这种情况下,for循环比.forEach()甚至.map()更好的原因是,在异步函数中,这些等待表达式实际上将等待,直到每个承诺都得到满足,然后才继续进行下一次迭代。(显然,在真正的代码中,您需要处理异常等。)


Sometimes you don't need to sequence things. In such cases, using .map() to collect a bunch of Promise objects that can then used with await Promise.all(collected) is great. But when you do want a strict one-before-the-other sequence, a plain loop is the best bet.

有时,您不需要对事物进行排序。在这种情况下,使用.map()收集一组Promise对象,然后这些对象可以与aWait Promise.all(Collect)一起使用。但当您确实想要一个严格的先有一个序列时,简单的循环是最好的选择。



To achieve dynamic chaining of POST requests based on the number of items in the commandPayloads array, you can use a recursive approach with Promises. Here's an example of how you can do it:

要根据命令有效负载数组中的项数实现POST请求的动态链接,您可以使用带有承诺的递归方法。下面是一个如何做到这一点的例子:



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


This code defines a sendSequentialRequests function that sends POST requests one by one in a sequential manner using Promises. It starts by sending the first request, and when that request is resolved, it calls itself recursively with the next index until all requests are sent. The .then() and .catch() at the end handle the completion or error of the entire sequence of requests.

这段代码定义了一个sendSequentialRequest函数,该函数使用Promise以顺序的方式逐个发送POST请求。它从发送第一个请求开始,当该请求被解析时,它用下一个索引递归地调用自己,直到发送完所有请求。结尾处的.Then()和.Catch()处理整个请求序列的完成或错误。


更多回答

Or use a not-as-old-fashioned for (const thing of listOfThings) loop

或者使用不太过时的for(Const Thing Of ListOfThings)循环

@Bergi yea that would work too of course, I'm sticking to the basics this weekend

@Bergi是的,这也会起作用,当然,这个周末我坚持基本的

This is much more complicated than simply using await in a for loop.

这比简单地在for循环中使用await要复杂得多。

Yes Using await is perfect

是的,使用等待是完美的

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

您的回答可以通过补充支持信息进行改进。请编辑以添加更多细节,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以在帮助中心找到更多关于如何写好答案的信息。

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com