1. Как написать Promises синхронно в узле, чтобы я мог получить желаемый результат. Я новичок и буду признателен за любую помощь/предложение.Как написать синхронную функцию в узле, используя 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.*/
Обещания по определению async, вы можете * (делать) * возвращать обещание синхронно, но обещанное значение ** всегда ** разрешено async. – Thomas
Обещание не может быть синхронным, а синхронный код вообще не нуждается в обещании, так что это мало смысла? – adeneo
Вы решаете немедленно с помощью 'missingArray' var внутри вашего обещания. 'request' является асинхронным, поэтому ваш push будет вызван после того, как обещание будет разрешено, следовательно, пустой массив будет тогда функционировать. Что вам нужно, так это 'Promise.all', обернутый вокруг запросов для всех userIds. –