Nodejs问题发送响应异步功能和请求发布

时间:2019-12-27 16:04:15

标签: node.js asynchronous request

我对发布请求的异步功能有疑问。我没有成功发送回字符串值。

这是代码

exports.GetQuote = async (req, res, next) => {
  try{  

   var dim = req.body.dimension;
   test = new sreq({ ** A LOT OF DATA **  })
   const data = JSON.stringify(test);
   request.post({
        headers: { 'content-type': 'application/json' },
        url: 'https://www.xxxx.com/API',
        body: data
    }, (error, res, body) => {
        if (error) {
            console.error(error)
            console.log('ERROR REQUEST');
            return
        }
          datares = JSON.parse(body);
        console.log(datares.value+" "+datares.Code); ***VALUE IS OK***
        response = datares.value+" "+datares.Code;  
        return response; *** NOT RETURN VALUE ***
    });
      }catch (e){
    console.error(e);
  }
}

console.log在nodejs控制台中是正确的,但是不返回值?

我错过了什么吗?

感谢帮助

2 个答案:

答案 0 :(得分:0)

使用async函数可暂停代码的执行,因此您无需回调。就像使用电话一样,您可以告诉另一个人给您回电,或者在他完成设置您的任务后等待他返回电话。

因此对于异步功能,代码看起来可能像这样。

exports.GetQuote = async (req, res, next) => {
    try {
        // dim variable not used -- > delete
        var dim = req.body.dimension;

        test = new sreq({ /** A LOT OF DATA **/ })
        const data = JSON.stringify(test);

        // code stops running until response is here
        let response = await request.post({
            headers: { 'content-type': 'application/json' },
            url: 'https://www.xxxx.com/API',
            body: data
        })

        // error handling I can't say 
        // since I don't know what is returned here if the call should fail
        if(response){
            datares = JSON.parse(response.body);
            console.log(datares.value + " " + datares.Code);  /*** VALUE IS OK ***/
            response = datares.value + " " + datares.Code;  // sets to the response var we defined above
            return response; // Return here
        } else{
            throw new Error({msg: `something went wrong`})
        }

    } catch (e) {
        console.error(e);
    }
}

请注意,exports.GetQuote现在拥有由async函数隐式返回的Promise。

答案 1 :(得分:-1)

您没有捕获返回值。您可以在回调函数之外定义一个变量。

exports.GetQuote = async (req, res, next) => {
  try{
   let response;

   var dim = req.body.dimension;
   test = new sreq({ ** A LOT OF DATA **  })
   const data = JSON.stringify(test);
   request.post({
        headers: { 'content-type': 'application/json' },
        url: 'https://www.xxxx.com/API',
        body: data
    }, (error, res, body) => {
        if (error) {
            console.error(error)
            console.log('ERROR REQUEST');
            return
        }
          datares = JSON.parse(body);
        console.log(datares.value+" "+datares.Code); ***VALUE IS OK***

        response = datares.value+" "+datares.Code;  // sets to the response var we defined above
    });
      }catch (e){
    console.error(e);
  }

  return response; // Return here
}