1.如何在Node中同步写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.*/
答案 0 :(得分:2)
var Promise = require('bluebird');
var request = require('request-promise');
var compareData = function(userIdArray) {
//Promise.all():
//takes an array of promises (and/or values),
//returns a promise of the resolved array
return Promise.all(
userIdArray.map(function(id){
return request({
method: 'POST',
url: 'http://localhost:6006/test1',
headers: { 'content-type': 'application/json' },
body: { email: id },
json: true
});
})
);
}
有什么需要进一步解释的吗?
答案 1 :(得分:2)
如果你不想根据@Thomas的回答使用外部库,你可以直接使用本机Promise - 而且它不是太冗长
var compareData = function compareData(userIdArray) {
return Promise.all(userIdArray.map(function (id) {
return new Promise(function (resolve, reject) {
var options = {
method: 'POST',
url: 'http://localhost:6006/test1',
headers: {
'content-type': 'application/json'
},
body: {
email: id
},
json: true
};
return request(options, function (error, response, body) {
error ? reject(error) : resolve(body);
});
});
}));
};
compareData(userIdArray)
.then(function (missingArray) {
console.log("The Body is: " + missingArray);
});
或者,因为这是节点,可以处理更现代的代码:
var compareData = userIdArray =>
Promise.all(userIdArray.map(id =>
new Promise((resolve, reject) =>
request({
method: 'POST',
url: 'http://localhost:6006/test1',
headers: {
'content-type': 'application/json'
},
body: {
email: id
},
json: true
}, (error, response, body) => error ? reject(error) : resolve(body))
)
));
compareData(userIdArray)
.then(missingArray =>
console.log("The Body is: "+ missingArray)
);
答案 2 :(得分:0)
没有库,并假设request
尚未返回承诺
var compareData = function(userIdArray) {
return Promise.all(
userIdArray.map(function(id) {
var options = {
method : 'POST',
url : 'http://localhost:6006/test1',
headers : { 'content-type': 'application/json' },
body : { email: id },
json : true
};
return new Promise(function(resolve, reject) {
request(options, function(error, response, body) {
if (error) {
reject();
} else {
resolve(body);
}
});
});
})
);
}
compareData(userIdArray).then(function(missingArray) {
console.log(missingArray);
});