3

My requirement is like this

  1. I want to run an axios call.
  2. I don't want to block the code until it finished.
  3. Also I don't want to know it's 200 or 500

This is my experiment code.

function axios() {
  console.log("axios calling...");
  return new Promise((resolve, reject) => {
    setTimeout(function() {
      resolve(console.log("DONE!"));
    }, 10000);
  });
}

function run() {
  axios();
  console.log("Before");
  return;
  console.log("This should never log");
}

run();

According to this experiment I think even though I return from the function still that promisified function is run. Which means it guaranteed call the axios.

My concern is, if axios take 10 mins established connection with the API (NOT SEND THE POST REQUEST) if I return from the next line will axios wait that 10 mins and send the request or break the connection establishing when I return?

margherita pizza
  • 6,623
  • 23
  • 84
  • 152
  • You can see in your own logs that your function returns right after logging `Before`. The axios function keeps running for the next 10 seconds and doesn't exit until it resolves. So your hypothesis is correct. – Nabeel Mehmood Aug 30 '19 at 06:19
  • because `Promise` is the eventual completion (or failure) of an asynchronous operation, it acts apart from your code, like in your experiment, meaning that even after 10 min, the connection will be established. In short: `return` from the function that created the promise, does **not** break the promise. – Omri Attiya Aug 30 '19 at 06:21
  • check https://stackoverflow.com/a/55999524/9381809 – AZ_ Aug 30 '19 at 06:23
  • https://stackoverflow.com/questions/51007636/how-javascript-single-threaded-and-asynchronous – Dan Aug 30 '19 at 06:32

1 Answers1

0

A promise will wait for data regardless of weather you call .then() on it or not (note that there are some exceptions[1] ). And the page will continue processing and wait for events as long as it's opened.

So if the request takes 10 minutes it will continue waiting (barring timeouts on either the server, gateway, router or browser) until you close the page/tab.

[1] Some libraries only triggers promise creation when you call .then() for example knex will keep returning a query object instead of a promise until you call .then() on the query object)

slebetman
  • 109,858
  • 19
  • 140
  • 171