1. Wie schreibt man Versprechen im Knoten, so dass ich meine gewünschte Ausgabe bekommen kann. Ich bin ein Neuling und würde jede mögliche Hilfe/Vorschlag schätzen.Wie schreibe ich eine synchrone Funktion in Node mit Promises
// This is my core function
var compareData = function(userIdArray) {
return new Promise(function(resolve, reject) {
var missingArray = new Array();
userIdArray.forEach(function(id) {
var options = {
method: 'POST',
url: 'http://localhost:6006/test1',
headers:{
'content-type': 'application/json' },
body: { email: id },
json: true
};
request(options, function (error, response, body) {
missingArray.push(body);
});
});
resolve(missingArray);
});
}
//I'm calling my function here
compareData(userIdArray)
.then(function(missingArray){
console.log("The Body is: "+ missingArray);
});
/* I expect the console.log to print the missingArray with data from my POST call,
but it prints an empty array. Can someone please tell me how to do this synchronously.
I'm pretty new to Node and finding it difficult to understand.*/
Versprechen sind per Definition async, Sie können * das Versprechen * synchron zurückgeben, aber der versprochene Wert ist ** immer ** aufgelöst async. – Thomas
Ein Promise kann nicht synchron sein, und synchroner Code benötigt im Allgemeinen kein Versprechen, also macht das wenig Sinn? – adeneo
Sie lösen sofort mit dem 'missingArray' var in Ihrem Versprechen. 'request' ist async, also wird Ihr Push aufgerufen, nachdem das Versprechen aufgelöst wurde, daher das leere Array in der Funktion. Was Sie brauchen, ist ein 'Promise.all', das sich um Anfragen für alle userIds dreht. –