我该如何使其成为异步函数

时间:2019-03-26 04:58:35

标签: javascript node.js

当我运行下面的代码时,我得到仅异步功能支持等待的错误。我如何使下面的异步成为我的路由异步,但是我想是因为我在异步函数中调用了一个Promise,所以我需要使该异步成为异步。下面是路线

contactRoutes.get('/:id', async(req, res) => {

    cb.getDoc(req.bucket, req.params.id ).then(result=>{

        var tasks = await cb.n1qlQuery_wId(req.bucket,req.N1qlQuery, cbQ.qContactTasks,req.params.id)
        console.log(JSON.stringify(tasks))

        res.json({ Success: true , Error: "", Message:"", Data: result.value})

       }).catch(err=>{
           res.json({ Success: false , Error: err, Message: ""})

       })


})

5 个答案:

答案 0 :(得分:3)

尝试一下:

contactRoutes.get('/:id', async(req, res) => {
    try{
        let result = await cb.getDoc(req.bucket, req.params.id );
        let tasks = await cb.n1qlQuery_wId(req.bucket,req.N1qlQuery, cbQ.qContactTasks,req.params.id)
        console.log(JSON.stringify(tasks))
        res.json({ Success: true , Error: "", Message:"", Data: result.value})
    }
    catch(err){
        res.json({ Success: false , Error: err, Message: ""})
    }

})

答案 1 :(得分:2)

您必须像这样将aync回调传递到您的承诺解析器then中,

contactRoutes.get('/:id', async(req, res) => {

    cb.getDoc(req.bucket, req.params.id ).then(async (result)=>{
         ...........
    }

})

或者您也可以像这样在您的承诺电话中使用await

contactRoutes.get('/:id', async (req, res) => {
  var result = await cb.getDoc(req.bucket, req.params.id)
  var tasks = await cb.n1qlQuery_wId(req.bucket, req.N1qlQuery, cbQ.qContactTasks, req.params.id)
  console.log(JSON.stringify(tasks))

  res.json({ Success: true, Error: "", Message: "", Data: result.value })
}).catch(err => {
  res.json({ Success: false, Error: err, Message: "" })
});

答案 2 :(得分:0)

.then中使回调函数异步。参见下面的代码。

contactRoutes.get('/:id', async(req, res) => {

cb.getDoc(req.bucket, req.params.id ).then(async result=>{

    var tasks = await cb.n1qlQuery_wId(req.bucket,req.N1qlQuery, cbQ.qContactTasks,req.params.id)
    console.log(JSON.stringify(tasks))

    res.json({ Success: true , Error: "", Message:"", Data: result.value})

   }).catch(err=>{
       res.json({ Success: false , Error: err, Message: ""})

   })


})

答案 3 :(得分:0)

您已将async添加到then(...)的处理程序中,而不是路由中。为什么?因为,在该处理程序中使用了await。

答案 4 :(得分:0)

您可以这样做:

  contactRoutes.get('/:id', async(req, res) => {
    try {
      const result = await cb.getDoc(req.bucket, req.params.id )

      var tasks = await cb.n1qlQuery_wId(req.bucket,req.N1qlQuery, cbQ.qContactTasks,req.params.id)
      console.log(JSON.stringify(tasks))

      res.json({ Success: true , Error: "", Message:"", Data: result.value})

    } catch (err) {
        res.json({ Success: false , Error: err, Message: ""})
    }
  })