如何在Sails.js中从此方法返回n的值

时间:2017-05-22 13:59:07

标签: javascript node.js sails.js

getCount: (filter = null) => {
  var whereConditions = {};
  if(filter != null) whereConditions.role = filter;

  User
    .count({
      where: whereConditions,
    })
    .exec((err, n) => {
      console.log(n);
      return n;
    });
}

上面的方法在调用时会返回undefined,但是当我在console.log n时,我得到了正确的输出。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

where()应返回promise,这意味着您可以在调用{"服务&#34} then()的代码中使用catch()getCount(filter) ;根据需要访问值和错误的成功响应。根据{{​​3}},.exec()可以直接替换为then()catch()。尝试以下内容:

<强>服务

getCount: (filter = null) => {
  var whereConditions = {};
  if(filter != null) whereConditions.role = filter;

  // return promise
  // using this value directly will not allow you to access queried values
  return User.count({ where: whereConditions });
}

<强>控制器/来电:

this.someService.getCount('someFilterValue')
  .then(values = {
      console.log(values);
      // do something with values like bind to variable/property of the view
  })
  .catch(error => console.log(error));

或者根据你的结构,你可以尝试这样的事情来做getCount()内的所有事情:

getCount: (filter = null) => {
  var whereConditions = {};
  if(filter != null) whereConditions.role = filter;

  // return promise
  // using this value directly will not allow you to access queried values
  return User
      .count({ where: whereConditions })
      .then(values => res.json(values))
      .catch(error => res.serverError(error));
}

您可以将then() getCount()中的功能委托给另一种方法来减少重复:

 getCount: (filter = null) => {
  var whereConditions = {};
  if(filter != null) whereConditions.role = filter;

  // return promise
  // using this value directly will not allow you to access queried values
  return User
      .count({ where: whereConditions })
      .then(handleResponse)
      .catch(error => res.serverError(error));
},

handleResponse: (data) => {
  // do something with data
  return data.map(e => e.someProperty.toUpperCase());
}

您可以根据需要链接then(),以便在每次返回转换后的值时根据需要继续转换值。只要继续返回值,就可以将其委托给方法。这也可以让你采取异步操作,只有在解决后才对它们采取行动。

getCount: (filter = null) => {
  var whereConditions = {};
  if(filter != null) whereConditions.role = filter;

  // return promise
  // using this value directly will not allow you to access queried values
  return User
      .count({ where: whereConditions })
      .then(values => values.map(e => e.someProperty.toUpperCase()))
      .then(transformedValues => transformedValues.filter(e => e.indexOf(filter) > -1))
      .then(filteredValues => res.json(filteredValues))
      .catch(error => res.serverError(error));
}

希望这有帮助!