Navaj Sheikh
Navaj Sheikh

Reputation: 19

helper function in node js

I wrote this helper function. it working but the problem is that it is not working without forloop and if I use any other method it returns [object promiss] how can I solve this please help me

I used other methods but it gives me [object promiss] as output

.js file

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();
    }
  })
});

.ejs file

<p> <%= contrycode("93"); %></p> ///function calling

Upvotes: 1

Views: 360

Answers (1)

Arpit Kumar
Arpit Kumar

Reputation: 2249

There is really no need of for-loop, you can easily find that country with the find method:

    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"
         }

      }

Please update your code.

I hope it will help.

Upvotes: 1

Related Questions