以下是使用promise的node.js中的函数。
exports.getDetailsByUserId = function(req,res) {
getUserDetails(req, res) // function to get user details
.then(function (Details) {
var allpromises = Details.map(getStatus); //get and update the status of user
return allpromises
})
.then(function (promises) {
var orderresult =[];
Q.allSettled(promises)
.then(function (allpromises) {
orderresult.push(allpromises);
})
return orderresult;
})
.then(function (result) {
getUserDetails(req, res)//again calling get user details so that i will get modified result
.then(function (data) {
res.json({
"User" : data
})
})
})
.catch(function (error) {
console.log(error);
res.status(200).json({
"Message": error
})
})
}
var getStatus = function (data,req) {
var deferred = Q.defer();
requestify.post('http://example.com', {
"data": [{ "Number": No }]
})
.then(function (response) {
response.getBody();
response.body;
var Status = JSON.parse(response.body);
var Details = { "_id": data._id, "Status": Status.status[0] };
return OrderDetails;
})
.then(function (DetailsData){
var req = { body : { Details :DetailsData} };
updateDetails(req).then(function (data) {
deferred.resolve;
})
})
.catch(function (error) {
deferred.resolve(error);
});
return deferred.promise;
}
getUserDetails
函数获取用户第一次的详细信息,然后getStatus
调用另一个API并更新相关的用户状态。到目前为止,每件事情都运转良好。
我需要第二次调用getUserDetails
来获取更新结果,但它不会提供更新结果。也许在更新状态之前调用它?代码可能出错,以便在Q.all
之后执行?
谢谢。
答案 0 :(得分:0)
var orderresult =[]; Q.allSettled(promises) .then(function (allpromises) { orderresult.push(allpromises); }) return orderresult;
你因经典mutation in asynchronous callback问题而堕落。 then
回调是异步的,orderresult
在返回时不会包含allpromises
数组。为了让某些东西等待承诺,你必须return
。
无论如何,您应该将代码简化为
getUserDetails(req, res)
.then(function (details) {
var allpromises = details.map(getStatus);
return Q.allSettled(allpromises); // just call it here already and return a promise
})
.then(function (allpromiseresults) {
var orderresult = [allpromiseresults]; // not sure what this is good for
return orderresult;
})
.then(function (result) { // given that you don't use the `result` anyway
return getUserDetails(req, res);
}).then(function (data) {
res.json({
"User" : data
})
}, function (error) {
console.log(error);
res.status(200).json({
"Message": error
})
});
并且在getStatus
中你应该避免使用deferred antipattern:
function getStatus(data,req) {
return requestify.post('http://example.com', {
"data": [{ "Number": No }]
})
.then(function (response) {
response.getBody(); // ???
var status = JSON.parse(response.body);
var details = { "_id": data._id, "Status": Status.status[0] };
// no `OrderDetails`, no `DetailsData`
var req = {body: {Details: details}};
return updateDetails(req) // probably "getStatus" should be called "updateStatus"
});
}