Event Stream Contour with Async / Await

I experimented with Async / Await commands in Javascript and noticed what I was confused about.

When I run the following code in Visual Studio code in debug mode, after I get to the first line of the wait code, it will move to the end of the function and then continue sequentially through the rest of the code, including the other β€œwaiting” lines. Why is this?

const axios = require("axios");
const apiURL = 'https://jsonplaceholder.typicode.com/posts/1'

async function multipleRequestsAsync() {
  try {
    console.log("starting...")
    const response1 = await axios.get(apiURL);
    console.log(response1.data);
    const response2 = await axios.get(apiURL);
    console.log(response2.data);
    const response3 = await axios.get(apiURL);
    console.log(response3.data);
  } catch (error) {
    console.error(error);
  }
}

multipleRequestsAsync();

Here is the code in jsfiddle .

Here is an animated gif of what I'm talking about. enter image description here

+4
source share
1 answer

, , , . async function, , await .

async function multipleRequestsAsync() {
  try {
    console.log("starting...");                // 3
    const response1 = await axios.get(apiURL); // 4
    console.log("done");                       // 7
  } catch (error) {
    console.error(error);
  }
}                                              // 5

console.log("before start");                   // 1
const promise = multipleRequestsAsync();       // 2
console.log("continuing...");                  // 6

before start
starting...
continuing
// later:
done

(5) await (4) (6).

+2

Source: https://habr.com/ru/post/1695185/


All Articles