简体   繁体   English

如何使承诺更加易读?

[英]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.

相关问题 如何将此正则表达式拆分为更具可读性? - How can I split this regex up to make more readable? 如何使此发布/子代码更具可读性? - How can I make this pub/sub code more readable? 如何在自定义异步函数中使用jQuery Promise? - How can I make use of jQuery promises in custom async functions? 如何使 React Components Dev 工具更易读/更有用? - How can I make the React Components Dev tool readable / more useful? 如何在我的react组件中重构此ASYNC调用以使其更具可读性? - How can I refactor this ASYNC call in my react component to make it more readable? 如何在不损失性能的情况下缩小或至少使我的代码更具可读性? - How can I minify or at least make my code more readable without losing on performance? 如何使 javascript map、减少语法更短、更易读? - How can I make the javascript map, reduce syntax shorter and more readable? 如何使用setTimeout和promises使此JS代码更具功能性? - How can I make this JS code more functional using setTimeout and promises? 你怎么能重构并使反应变得不那么笨重和可读性? - How can you refactor and make react less bulky and more readable? 我如何制作瀑布Q承诺? - How can I make a waterfall Q promises?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM