So verketten und teilen Sie frühere Ergebnisse mit Promises [duplicate]
Diese Frage hat hier bereits eine Antwort:
Wie greife ich auf frühere Versprechungsergebnisse in einer .then () -Kette zu? 15 answers Ich benutze die Bluebird-Bibliothek und muss eine Reihe von HTTP-Anfragen stellen und einige der Antwortdaten zur nächsten HTTP-Anfrage benötigen. Ich habe eine Funktion namens @ erstellt, die meine Anfragen bearbeitecallhttp()
. Dies erfordert eine URL und den Body eines POST.
Ich rufe es so an:
var payload = '{"Username": "joe", "Password": "password"}';
var join = Promise.join;
join(
callhttp("172.16.28.200", payload),
callhttp("172.16.28.200", payload),
callhttp("172.16.28.200", payload),
function (first, second, third) {
console.log([first, second, third]);
});
Die erste Anfrage erhält einen API-Schlüssel, der an die zweite Anfrage weitergegeben werden muss und so weiter. Wie erhalte ich die Antwortdaten aus der ersten Anfrage?
AKTUALISIERE
Dies ist dascallhttp
Funktion:
var Promise = require("bluebird");
var Request = Promise.promisify(require('request'));
function callhttp(host, body) {
var options = {
url: 'https://' + host + '/api/authorize',
method: "POST",
headers: {
'content-type': 'application/json'
},
body: body,
strictSSL: false
};
return Request(options).spread(function (response) {
if (response.statusCode == 200) {
// console.log(body)
console.log(response.connection.getPeerCertificate().subject.CN)
return {
data: response.body
};
} else {
// Just an example, 200 is not the only successful code
throw new Error("HTTP Error: " + response.statusCode );
}
});
}