带有axios的GET请求返回未定义

bla*_*rix 2 javascript asynchronous http typescript

我正在尝试使用以下命令执行获取请求:

router.get('/marketUpdates',((request, response) => {
  console.log("market updates");
  var data: Order[]
  axios.get('http://localhost:8082/marketUpdates')
  .then(function (response) {
    console.log("GET Response")
    console.log(response.data);
    data = response.data;
  })
  .catch(function (error) {
    console.log("Error in fetching market updates");
  });  

  console.log("Data before sending is ")
  console.log(data);
  response.send(data);
}))
Run Code Online (Sandbox Code Playgroud)

但是,我靠近底部的console.log在.then中的console.log之前执行。

数据在发送时是不确定的。有谁知道我能避免这种情况?

M U*_*M U 5

  1. 该代码是异步的,因此在请求等待响应时,请求下面的所有代码都会被执行。您可以仅从底部将日志移到axios.get
  2. 您内部的数据thendata发送的数据不同...您正在使用function(response)而不是箭头功能。(response) => {}所以您要绑定另一个。

尝试这种方式:

router.get('/marketUpdates',((request, response) => {
  console.log("market updates");
  let data: Order[]
  console.log("Data before sending is ")
  console.log(data);
  axios.get('http://localhost:8082/marketUpdates')
  .then((getResponse) => {
    console.log("GET Response")
    console.log(getResponse.data);
    data = getResponse.data;
    response.send(data);
  })
  .catch(function (error) {
    console.log("Error while fetching market updates");
  });  
}))
Run Code Online (Sandbox Code Playgroud)


Joh*_*auß 5

发送到服务器的请求总是异步的。这意味着,该函数.then()将在服务器响应时执行。

让我重新格式化您的代码:

router.get('/marketUpdates',((request, response) => {
  console.log("market updates");

  var data: Order[];

  console.log("Data before sending is ")
  console.log(data);

  axios.get('http://localhost:8082/marketUpdates')
  .then((response) => {
    console.log("GET Response")
    console.log(response.data);
    data = response.data;

    response.send(data);
  })
  .catch(function (error) {
    console.log("Error in fetching market updates");
  });  
}))
Run Code Online (Sandbox Code Playgroud)

通过该行,axios.get('http://localhost:8082/marketUpdates')您正在向服务器发出请求,服务器将做出响应,但这需要时间。JavaScript 不会停止执行函数以在程序等待服务器响应时保持用户界面运行。

So .get returns a Promise, that holds several function that get invoked in different scenarios. The function that is given as first parameter to .then will be invoked as soon as the server returned 200 and a response.

That means that your logs at the bottom of the code will be executed as soon as axios triggers the call to the server. At this point there is no data, because the server hasn't reacted yet.

  • 几乎同时出现 2 个类似的答案:) (5认同)