我试图找出如何纠正使用promises重写我的函数。 原始工作版本如下:
this.accountsAPI.find(filter, function(err,result){
if (err || 0 == result.length) {
return res.status(400).json({error: "Can't find the account."});
}
var workRequest = req.query.workRequest;
// result has some records and we assume that _id is unique, so it must have one entry in the array
var newJob = { jobId: workRequest, acceptedById: result[0]._id, dateCreated: new Date() };
this.jobsAPI.create( newJob, function(jobErr, jobResult) {
if (jobErr) { return res.status(400).json({error: "Can't create a new job."}); }
res.status(200).json({newJob});
});
});
我把它重写为:
return new Promise(function ( fulfill, reject) {
this.accountsAPI.find(filter)
.then(function (result) {
if (0 == result.length) { return res.status(400).json({error: "Can't create a new job."}); }
var workRequest = req.query.workRequest;
// result has some records and we assume that _id is unique, so it must have one entry in the array
var newJob = { workRequestId: workRequest, acceptedById: result[0]._id, dateCreated: new Date() };
this.jobsAPI.create( newJob, function(jobErr, jobResult) {
if (jobErr) { return res.status(400).json({error: "Can't create a new job."}); }
res.status(200).json({newJob});
})
})
.catch((err) => {
return res.status(400).json({
error: "Can't create a job.",
errorDetail: err.message
});
});
不正确我正确编码了promise版本。但是,即使我这样做,仍然存在链式异步请求,因此我的Promise版本只会让事情变得更复杂。
我应该使用承诺进行此类通话吗?有没有办法优雅地重写我的代码?
答案 0 :(得分:2)
不,在Promise
构造函数中包装所有内容并不会自动使其正常工作。
您应该从最低级别使用的promisifying the asynchronous functions开始 - 在您的情况下,accountsAPI.find
和this.jobsAPI.create
。只有这样,您才需要Promise
构造函数:
function find(api, filter) {
return new Promise(function(resolve, reject) {
api.find(filter, function(err, result) {
if (err) reject(err);
else resolve(result);
});
});
}
function create(api, newJob) {
return new Promise(function(resolve, reject) {
api.create(newJob, function(err, result) {
if (err) reject(err);
else resolve(result);
});
});
}
如您所见,这有点重复,您可以为此编写辅助函数;但如果您使用的承诺库不仅仅是ES6 polyfill,它可能已经提供了一个。
现在我们有两个函数find
和create
,它们将返回promises。有了这些,你可以将你的功能重写为一个简单的
return find(this.accountsAPI, filter).then(function(result) {
if (result.length == 0)
throw new Error("Can't find the account.");
return result;
}, function(err) {
throw new Error("Can't find the account.");
}).then(function(result) {
// result has some records and we assume that _id is unique, so it must have one entry in the array
return create(this.jobsAPI, {
jobId: req.query.workRequest,
acceptedById: result[0]._id,
dateCreated: new Date()
}).catch(function(err) {
throw new Error("Can't create a new job.");
});
}.bind(this)).then(function(newJob) {
res.status(200).json(newJob);
}, function(err) {
res.status(400).json({error:err.message});
});