我写了这个辅助函数。它可以工作,但问题是没有 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();
}
})
});
.ejs文件
<p> <%= contrycode("93"); %></p> ///function calling
最佳答案
真的不需要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"
}
}
请更新您的代码。
希望对您有所帮助。
关于javascript - Node js中的辅助函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57284666/