Ich benutze Anfrage-Bibliothek, um mit anderen Servern über API zu kommunizieren. Aber jetzt muss ich mehrere (10 oder mehr) POST-Anfragen zur gleichen Zeit senden und nur weitergehen, wenn alle Antworten korrekt sind. Normalerweise sieht Syntax etwas wie folgt aus:Node.js Anfrage - Behandlung mehrerer POST-Anfragen
var options = {
url: "",
method: "POST",
header: {...},
body: {...}
};
request(options, function(err,response,body)
{
}
Aber jetzt habe ich eine Reihe von Objekten statt einer einzigen Optionen Variable bekam. Gibt es eine Möglichkeit, dies zu tun? Oder vielleicht gibt es eine andere Bibliothek, die das Problem lösen kann.
EDIT:
var arrayOfIds = [];
const requests = [];
for(var i in range){
var options = {} // here goes all bodies and headers to send
requests.push(// push a request to array dynamically
request(options, function(err,response,body){
if(!err && response.statusCode == 201){
arrayOfIds.push(body.id);
}
}));
Promise.all(requests)
.then(function(res){
console.log(arrayOfIds); // this is empty
});
Mögliches Duplikat [Schleife durch asynchrone Anforderung] (https://stackoverflow.com/questions/44636542/loop-through-asynchronous-request) –