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'。 –