1.如何在节点中同步写入Promises,以便获得所需的输出。我是一个新手,并会感谢任何帮助/建议。如何在使用Promise的节点中编写同步功能
// 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.*/
承诺是按定义异步,你可以*(做)*同步返回承诺,但承诺的价值是**总是**解决异步。 – Thomas
Promise不能同步,并且同步代码通常不需要承诺,所以没有多大意义? – adeneo
您正在使用承诺中的'missingArray' var立即解决问题。 'request'是异步的,所以你的push将在promise被解析后被调用,因此在then函数中是空的数组。你需要的是一个包含所有用户标识请求的'Promise.all'。 –