如何获取回调函数[API请求的return值

How to get the return value of a callback function [API Request]

我想执行 API 请求并在我的网站上的 table 中显示正文。我正在使用 Node.JS、React 和 Request。这是我的代码:

var requestResult = Request.get('https://test.ipdb.io/api/v1/assets/?search=asdf', (err, res, body) => {
  return body;
});

这显然是行不通的。我可以 console.log(body),但我希望 API 响应在回调函数之外可用。这可能吗?

如果您使用的是回调方法,那么您应该继续回调函数的工作。
示例:

app.get('/', function(req, res, next) {
  Request.get('https://test.ipdb.io/api/v1/assets/?search=asdf', (err, res, body) => {
    console.log(body);
    // do any other job here
    res.send(body);
  });
});

您可以在 2017 年使用的其他方法:

  • promises
  • 协程 + 生成器
  • 异步+等待

您可以获得更多信息here