Javascript 节点js中的helper函数

Javascript 节点js中的helper函数,javascript,node.js,express,Javascript,Node.js,Express,我编写了这个助手函数。它正在工作,但问题是没有forloop它就无法工作,如果我使用任何其他方法,它将返回[object promiss],我如何解决这个问题,请帮助我 我使用了其他方法,但它将[object promiss]作为输出 .js文件 app.use(function(req, res, next) { CountryData.find({}, function(err, result) { if (err) { console.log(err) }

我编写了这个助手函数。它正在工作,但问题是没有forloop它就无法工作,如果我使用任何其他方法,它将返回[object promiss],我如何解决这个问题,请帮助我

我使用了其他方法,但它将[object promiss]作为输出

.js文件

app.use(function(req, res, next) {
  CountryData.find({}, function(err, result) {
    if (err) {
      console.log(err)
    } else {

      res.locals.contrycode = function(code1) { //helper function

        for (var i = 0; i <= 500; i++) {

          if (result[i].phoneCode.toString() === code1) {
            return result[i].name.toString();
            break;
          }
        }

      }
      next();
    }
  })
});
app.use(函数(请求、恢复、下一步){
CountryData.find({},函数(err,result){
如果(错误){
console.log(错误)
}否则{
res.locals.contrycode=函数(代码1){//helper函数

对于(var i=0;i循环实际上不需要
for loop
,您可以使用find方法轻松找到该国家:

    res.locals.contrycode = function(code1) { //helper function

         var selectedCountry = result.find(function(country) {
           return country.phoneCode === code1;
         });

         if (selectedCountry) { // country found with this code
           return selectedCountry.name;
         } else {
           return "whatever you want"
         }

      }
请更新您的代码


我希望这会有所帮助。

因为您的结果是一个数组,所以您应该使用循环将code1与其中的每个对象进行比较。这看起来像是一种逻辑行为。我们应该像findOne({phoneCode:code1)这样更改查询;并且您将从db中只获得一个实例。
    res.locals.contrycode = function(code1) { //helper function

         var selectedCountry = result.find(function(country) {
           return country.phoneCode === code1;
         });

         if (selectedCountry) { // country found with this code
           return selectedCountry.name;
         } else {
           return "whatever you want"
         }

      }