[英]How can I make use of promises more readable?
I have the following code. 我有以下代码。 Is there a better way to write it.
有没有更好的方法来编写它。 It feels like when conditions and promises and querying from multiple tables are involved, the code becomes harder to read.
感觉就像涉及条件和承诺以及从多个表进行查询时,代码变得更难阅读。 Any help would be appreciated.
任何帮助,将不胜感激。 Thanks!
谢谢!
fetchUserById = function (id) {
var user = {};
return knex_instance('user_info')
.where('id', id)
.first()
.then(function (data) {
if (!data) {
return null;
} else {
user.info = data;
return knex_instance('user_table')
.where('id', id)
.first()
.then(function (values) {
user.values = values;
return user;
});
}
})
.catch(errorHandler('fetchUserById', id));
}
Instead of increasing the indentation level with each request, you can return the request to the original promise chain and add a then
there. 您可以将请求返回到原始的Promise链,
then
在其中添加一个,而不是增加每个请求的缩进级别。 Like this: 像这样:
fetchUserById = function(id) {
var user = {};
return knex_instance('user_info').where('id', id).first()
.then(function(data) {
if (!data)
return null;
user.info = data;
return knex_instance('user_table').where('id', id).first();
})
.then(function(values) {
if (!values)
return null;
user.values = values;
return user;
});
.catch(errorHandler('fetchUserById', id));
}
Problem with this approach, the null
that can be returned by the first then
must be passed through the second one (and the third, fourth, etc, if you had some). 问题这种方法,
null
,可以通过第一返回then
必须通过第二个传递(第三,第四等,如果你有一些)。 An alternate method would have been to use exceptions instead of returning null: 另一种方法是使用异常而不是返回null:
fetchUserById = function(id) {
var user = {};
return knex_instance('user_info').where('id', id).first()
.then(function(data) {
if (!data)
throw "NO_USER_INFO";
user.info = data;
return knex_instance('user_table').where('id', id).first();
})
.then(function(values) {
user.values = values;
return user;
});
.catch(function(err) {
if (err==="NO_USER_INFO")
return null;
else
return errorHandler('fetchUserById', id);
}
}
One way to increase readability is to separate part of the code into its own function. 提高可读性的一种方法是将部分代码分成自己的功能。
I don't know what this function does, so I'm just going to call it doSomething
. 我不知道此函数的作用,因此我将其称为
doSomething
。 If you replace that with something descriptive it's easier to read in two places: The function itself describes the code it contains, and the call to the function indicates what's happening at that step in the calling code. 如果将其替换为描述性内容,则很容易在两个地方阅读:函数本身描述了其中包含的代码,并且对该函数的调用指示了调用代码在该步骤中正在发生的事情。
function doSomething(data)
{
if (!data) {
return null;
} else {
user.info = data;
return knex_instance('user_table')
.where('id', id)
.first()
.then(function (values) {
user.values = values;
return user;
}
}
fetchUserById = function (id) {
var user = {};
return knex_instance('user_info')
.where('id', id)
.first()
.then(doSomething)
.catch(errorHandler('fetchUserById', id));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.