【问题标题】:Cannot respond the API call inside a call back function (in NodeJS request)无法在回调函数中响应 API 调用(在 NodeJS 请求中)
【发布时间】:2018-10-08 17:08:09
【问题描述】:

我的 NodeJS 中有这段代码。如果我将 return 放在 request.post 调用之前,我会得到响应,但在回调中我会得到 {data: null}。

exports.addItem = functions.https.onCall((req, context)=>{
  request.post(
  {url: submitUrl,
  form: req},
  function (error, response, body) {
      if (!error && response.statusCode == 200) {
          console.log(body);
          return {result: "OK"};
          }
      else{
        return {result: "Not OK"}
      }
      }
  );
});

如果有帮助,我会在 firebase 中运行此代码,并在我的 JS 中使用 firebase 函数调用它

【问题讨论】:

  • 不清楚这段代码的上下文是什么。但它看起来像 Express 中间件。如果您想发送回复,请直接致电res
  • 如何直接调用res?
  • 什么是res?你甚至没有确认它是快递。如果是则查看手册,expressjs.com/en/api.html#res

标签: javascript node.js post callback request


【解决方案1】:

return 将导致函数结束,但当它是这样的异步回调时,不会向用户发送任何内容。对于要返回的值,没有您可以控制的调用函数。

我不确定您要达到什么目的,但在这种情况下使用带有 return 的值会导致该值丢失。

如果您需要提高对 Node.js 中异步回调习语的理解,不妨查看https://blog.risingstack.com/node-hero-async-programming-in-node-js/

【讨论】:

  • 如果我使用 Promise 会有帮助吗?
【解决方案2】:

你应该使用 async/await 来解决这个问题

exports.addItem = functions.https.onCall(async (req, res)=>{
  await request.post(
  {url: submitUrl,
  form: req},
  function (error, response, body) {
      if (!error && response.statusCode == 200) {
          console.log(body);
          return {result: "OK"};
          }
      else{
        return {result: "Not OK"}
      }
      }
  );
});

【讨论】:

    猜你喜欢
    • 2012-09-27
    • 1970-01-01
    • 1970-01-01
    • 2018-01-29
    • 1970-01-01
    • 1970-01-01
    • 2018-10-08
    • 2021-03-28
    • 2019-08-30
    相关资源
    最近更新 更多