Z0q*_*Z0q 21 javascript multithreading node.js axios
此时我有一个网页,其中正在制作一长串 Axios POST 调用。现在,请求似乎是并行发送的(JavaScript 在收到结果之前继续发送下一个请求)。
但是,结果似乎是一个一个返回,而不是同时返回。假设对 PHP 脚本的一次 POST 调用需要 4 秒,而我需要进行 10 次调用。目前每次调用需要 4 秒,总共需要 40 秒。我希望找到解决方案并在大约同一时间(约 4 秒)而不是约 40 秒收到所有结果。
现在我已经阅读了关于线程,NodeJS 中使用 Workers 的多线程。我读过 JavaScript 本身只是单线程的,因此它本身可能不允许这样做。
但我不知道从哪里开始。我只有一些想法。我不确定我是否正朝着正确的方向前进,如果是,我不确定如何在 NodeJS 中使用 Workers 并将其应用到我的代码中。我应该走哪条路?任何指导将不胜感激!
这是一小段示例代码:
for( var i = 0; i < 10; i++ )
{
window.axios.post(`/my-url`, {
myVar: 'myValue'
})
.then((response) => {
// Takes 4 seconds, 4 more seconds, 4 more seconds, etc
// Ideally: Takes 4 seconds, returns in the same ~4 seconds, returns in the same ~4 seconds, etc
console.log( 'Succeeded!' );
})
.catch((error) => {
console.log( 'Error' );
});
// Takes < 1 second, < 1 more second, < 1 more second, etc
console.log( 'Request sent!' );
}
Run Code Online (Sandbox Code Playgroud)
Har*_*tel 39
有三种情况可以通过你实现你的目标。
对于使用 Axios 的同时请求,您可以使用 Axios.all()
axios.all([
axios.post(`/my-url`, {
myVar: 'myValue'
}),
axios.post(`/my-url2`, {
myVar: 'myValue'
})
])
.then(axios.spread((data1, data2) => {
// output of req.
console.log('data1', data1, 'data2', data2)
}));
Run Code Online (Sandbox Code Playgroud)
你可以使用Promise.allSettled(). Promise.allSettled() 方法返回一个在所有给定的承诺都已解决或被拒绝后解决的承诺,
您可以尝试使用,Promise.all()但它的缺点是,如果任何1 个请求失败,那么它将全部失败并给出 o/p 作为错误(或在 catch 块中)
但最好的情况是第一个。
小智 11
对于使用 Axios 的同时请求,您可以使用 Axios.all()。
axios.all([
axios.get('https://api.github.com/users/MaksymRudnyi'),
axios.get('https://api.github.com/users/taylorotwell')
])
.then(axios.spread((obj1, obj2) => {
// Both requests are now complete
console.log(obj1.data.login + ' has ' + obj1.data.public_repos + ' public repos on GitHub');
console.log(obj2.data.login + ' has ' + obj2.data.public_repos + ' public repos on GitHub');
}));
Run Code Online (Sandbox Code Playgroud)
此外,您可以使用 Promise.all()。类似的工作:
Promise.all([
fetch('https://api.github.com/users/MaksymRudnyi'),
fetch('https://api.github.com/users/taylorotwell')
])
.then(async([res1, res2]) => {
const a = await res1.json();
const b = await res2.json();
console.log(a.login + ' has ' + a.public_repos + ' public repos on GitHub');
console.log(b.login + ' has ' + b.public_repos + ' public repos on GitHub');
})
.catch(error => {
console.log(error);
});
Run Code Online (Sandbox Code Playgroud)
但是,使用 Promise.all() 有一个特定的行为。如果至少一个请求被拒绝 - 所有请求都将被拒绝,代码将转到 .catch() 部分。如果您需要确保所有请求都得到解决,那也没关系。
万一当您的某些请求被拒绝时可以考虑使用 Promise.allSettled()。所述Promise.allSettled()方法返回一个承诺,之后所有给定的承诺做出决议已经解决或拒绝,与对象的数组,每个描述每个承诺的结果。
如果你想在循环中使用它,你可以对 @deelink 的版本进行稍微修改,如下所示
let promises = [];
for (i = 0; i < 10; i++) {
promises.push(
window.axios.post(`/my-url`, {
myVar: 'myValue'})
.then(response => {
// do something with response
})
)
}
Promise.all(promises).then(() => console.log('all done'));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
37682 次 |
| 最近记录: |