我有相当大的数据,要通过节点获取发送到 api。但是,由于数组中有很多数据,我想并行发送数据,所以我想使用 promise.allSettled ... 然而,它仍然需要太多时间,并且执行卡住了。
我的代码是这样的:
const fetch = require('node-fetch');
// .....
// get tokens for API and after receiving the token, call function to send the data
await sendToApi(token);
// .....
async function sendToApi(token) {
// headers and requestOptions are defined above (uses token)
try {
const responses = await Promise.allSettled(
data.map(async (Item) => {
path = 'my/path/';
requestOptions.body = JSON.stringify(Item);
const res = await fetch(path, requestOptions);
console.log("res.status: ", res.status);
return res;
})
);
responses.forEach((response) => {
console.log("response.status: ", response.status);
});
} catch (error) {
console.log("error: ", error);
}
(如果数据很小,即当我截断数据数组时,上面的代码和 promise.allSettled 工作得很好。但是对于实际数据大小,处理所有的承诺需要很长时间并且也会卡住(停止做和等了很久之后我按下 cmd+C))
因此我想,如果我可以将数据分成更小的部分并将异步发送到一个包含 promise.allSettled 的函数,它可以做得很好......
这就是我试图做的......
这是蛮力,我的意思是,如果可行,我将编写更简洁的代码来处理逻辑...
// get tokens for API and after receiving the token, call function to send the data
await sendToApi(token);
// .....
async function sendToApi(token) {
// headers and requestOptions are defined above (uses token)
// data is the original big array (but for trial, even this is truncated)
await sendInGroups(data.slice(0, n), requestOptions);
await sendInGroups(data.slice(n + 1, 2 * n), requestOptions);
await sendInGroups(data.slice(2 * n + 1, 3 * n), requestOptions);
// .... it continues
以下,功能同上:
async sendInGroups(data), requestOptions) {
try {
console.log("in try");
const responses = await Promise.allSettled(
data.map(async (Item) => {
path = 'my/path';
requestOptions.body = JSON.stringify(Item);
const res = await fetch(path, requestOptions);
console.log("res.status: ", res.status);
return res;
})
);
responses.forEach((response) => {
console.log("response.status: ", response.status);
});
} catch (error) {
console.log(error);
}
}
}
所有的承诺返回“拒绝”...
此外,如果我将所有数据发送到此函数(我的意思是,即使我不对它们进行切片,承诺也会再次被拒绝!)
try/catch 不给我错误的原因。 (我也尝试了其他几个选项来捕获错误,但我无法实现...)
我的问题:
谢谢。
我想我解决了我的问题。
让我澄清一下,以便有一天它也可能对另一个人有用...
我试图将大量数据发送到 API。但首先我是按顺序做的,这花了很长时间……
然后,在网上搜索,我了解到,可以使用 promise.all 或 promise.allSettled 并行发送...
所以这是真的......但是,在我自己的情况下,我不需要 promise.all 或 promise.allSettled 的回应......因为我只关心发送数据......
等待 promise.all 或 promise.allSettled 的响应也需要相当长的时间..
所以真正的解决方案是使用“promise.any”。即使其中一个承诺被批准,它也会返回“fulfilled”...... 在这种情况下没有(或更少)时间延迟......
这里是一段代码:
const responses = await Promise.any(
vehData.map(async (vehItem) => {
path = 'my/path/';
// assign vehItem data to requestOptions...
const res = await fetch(path, requestOptions);
// console.log(res.status) // I only logged the outcome if it is NOT 201
请检查我在这里甚至没有使用“回复”..我不需要它..
感谢所有回答我问题的人。