所以我使用NodeJs“请求”模块发出多个帖子请求,我觉得好像我可能做错了。有没有更好的方法来解决这个问题?
假设我有一系列我需要发送的不同JSON实体。
var requests = [
{
"Subject": "TestSubject1",
"Body": "TestBody1",
"PreferredLanguage": "en-US",
"Recipients": [
{
"FirstName": "TestName1",
"EmailAddress": "TestEmail1"
}
]
},
{
"Subject": "TestSubject2",
"Body": "TestBody2",
"PreferredLanguage": "en-US",
"Recipients": [
{
"FirstName": "TestName2",
"EmailAddress": "TestEmail2"
}
]
},
{
"Subject": "TestSubject3",
"Body": "TestBody3",
"PreferredLanguage": "en-US",
"Recipients": [
{
"FirstName": "TestName3",
"EmailAddress": "TestEmail3"
}
]
}
]
以下是我尝试这样做的方法。
for(var i = 0; i < requests.length; i++){
request.post(
{
url: 'https://testURL.com/messages',
json: requests[i],
method: 'POST'
},
function (e, r, body) {
console.log(body);
}
)
}
我觉得这是解决这个问题的一种非常糟糕的方式。这样做的正确方法是什么?
答案 0 :(得分:0)
你可以这样做。一般来说,您希望避免进行大量的HTTP调用,因此如果您能够编辑要发出请求的API,则可以更改端点以获取数组(当前的access
数组)和在一个HTTP请求中返回您需要的所有内容。
答案 1 :(得分:0)
您不应盲目地向服务器发出数百个并行请求。
您应该对服务器的并行请求数量有一些限制,否则服务器可能会关闭或服务器可能会阻止您
我个人在这些情况下使用节点async
模块的eachLimit函数。
以下是工作代码
const async = require('async');
const request = require('request');
var limit = 2 //max 2 parallel request at time
var requests = [
{
"Subject": "TestSubject1",
"Body": "TestBody1",
"PreferredLanguage": "en-US",
"Recipients": [
{
"FirstName": "TestName1",
"EmailAddress": "TestEmail1"
}
]
},
{
"Subject": "TestSubject2",
"Body": "TestBody2",
"PreferredLanguage": "en-US",
"Recipients": [
{
"FirstName": "TestName2",
"EmailAddress": "TestEmail2"
}
]
},
{
"Subject": "TestSubject3",
"Body": "TestBody3",
"PreferredLanguage": "en-US",
"Recipients": [
{
"FirstName": "TestName3",
"EmailAddress": "TestEmail3"
}
]
}
]
function iteratee(requestBody, cb) {
//this will be called for each item in the requests array
console.log("request processing starts")
request.post({
url: 'https://testURL.com/messages',
json: requestBody,
method: 'POST'
},
function (e, r, body) {
console.log(e);
console.log(body);
cb();
console.log("request processing ends")
});
}
function finalCallback(err) {
//this will be called when all the requests are processed
}
async.eachLimit(requests, limit, iteratee, finalCallback)
答案 2 :(得分:0)
一切都取决于你的意图:
如果你需要处理请求,那么你很好。结果单独(所有请求都是异步的,将由传递的回调函数单独处理)。
但是,当我们完成所有请求时,您通常需要做出最终操作。您可以使用Promise.all。
例如:
require("request/package.json"); // request is a peer dependency.
const requestPromiseAny = require("request-promise-any");
const requests = [
{
"name": "morpheus",
"job": "leader"
},
{
"name": "tom",
"job": "leader"
}
];
Promise.all(requests.map((requestJSON) => {
return requestPromiseAny.post(
{
url: 'https://reqres.in/api/users',
json: requestJSON,
method: 'POST'
});
})).then((responses) => {
console.log(responses);
});
您可以在runkit上轻松试用。