[英]Correct chained promise syntax
我試圖弄清楚如何使用Promise正確重寫我的函數。 原始工作版本如下:
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版本只會使事情變得更復雜。
我應該在這些電話中使用諾言嗎? 有沒有辦法優雅地重寫我的代碼?
不,將所有內容包裝在Promise
構造函數中不會自動使其起作用。
你應該開始promisifying異步功能就是,在你的情況, -您正在使用的最低水平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
,它們將返回promise。 有了這些,您可以將函數重寫為簡單的
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});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.