<h1> <%= contrycode('93')%> </h1>

时间:2019-07-25 13:25:35

标签: node.js express async-await ejs

我想编写一个辅助函数。

node.js页面

app.locals.contrycode = async(name) => {
  const id = name
  var idi

  await CountryData.find({ phoneCode: id })
                    .then(contryname => {
                      idi = contryname[0].name
                      console.log(contryname[0].name)
                      console.log(contryname)
                      console.log("............")
                    }).catch(err => {
                      console.log(err)
                    })


  const name1 = idi
  console.log('test------ ', name1)
  return name1;
}

ejs页面

<h1><%= contrycode('93') %></h1> 

我得到输出=> [object Promise]

对此有什么解决方案?

1 个答案:

答案 0 :(得分:0)

尝试以下代码:

// USING PROMISIFIED FUNCTION
app.locals.contrycode = async(name) => {
    return new Promise((resolve,reject) => {
        CountryData.find({ phoneCode: id })
        .then(contryname => {
            idi = contryname[0].name
            resolve(idi) ;
            console.log("............")
        }).catch(err => {
            console.log(err)
        })
    })
}

// USING ASYNC/AWAIT
    app.locals.contrycode = async(name) => {
      const id = name
      var idi= 

      let contryname = await CountryData.find({ phoneCode: id })
      return contryname[0].name;
    }