What order does JavaScript async code get executed in?

Take a look at the angular code below:

// 1.
var value = 0;
// 2.
value = 1;

$http.get('some_url')
  .then(function() {
  // 3.
    value = 2;
  })
  .catch(function(){})

// 4.
value = 3

// 5.
value = 4

// 6.
$http.get('some_url')

Assuming that after statement 4, the $http request is completed.

Will statement 5 be executed next or will it be statement 3?

If statement 5 is executed next, does this imply that all subsequent statements will be executed before the thread becomes free?

If statement 3 is executed next, does this mean that the promise always interrupts the thread based on the order of calls?

What is the standard rule for execution order, and are there any exceptions for more complex scenarios like nested promises?

Answer №1

Although javascript makes use of an asynchronous event loop, the execution of javascript code is sequential and entirely predictable. The following is the order in which your code will be executed:

  1. something = 0
  2. something = 1
  3. $http.get('some_url')
  4. something = 3
  5. something = 4
  6. $http.get('some_url')

It's after step 6 where the execution could take different paths. The code will pause until one of the http requests finishes, then fulfill the promise for that request, triggering the function in your then statement. (Two requests cannot complete simultaneously due to javascript's sequential nature)

To address your question directly, javascript does not allow code execution to be interrupted. When a function is running, it continues until it returns. Any asynchronous tasks that finish during this time will only run after the function has completed. Different potential events like the one described above are handled in the order they were triggered, following a "first in first out" sequence.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The functionality of AngularJs routing does not seem to be operating as anticipated

Please check out my demo example on Plunker. I have been experimenting with integrating the AdminLTE template with AngularJs Routing. I have defined the routing rules in my app.js file as follows: app.config(function ($routeProvider, $locationProvider) { ...

Having trouble displaying json data in an HTML file with d3.js

I am having trouble loading data from a json file into an HTML file and using D3 to visualize it. Even though the file loads correctly and is verified with a 200 status, the contents are interpreted as null. Below are the contents of the json file: [{"to ...

Expecting a volumetric result can be deceiving when dealing with objects that have three flat

The problem at hand: When subtracting a cube from a sphere, an interesting result occurs where the z axis maintains its volume while the y and x axes create flat disks. This peculiar outcome is puzzling to me as I utilize the typical subtraction method wi ...

Dealing with browser timeouts for HTTP requests using JavaScript

Managing time out situations in a web application when calling a REST API is crucial. Below is the code snippet I am using to make the API call with jQuery ajax. $.ajax({ type: "POST", url: endpoint, data: payload, ...

How to trigger a submit action on a different page from an iframe using PHP

Is there a way to submit the iframe page using the modal's submit button in Page1.php to trigger the submit button of Page2.php? I need help executing this efficiently. The purpose of having the submit button in a modal is to perform multiple functio ...

Utilizing the Power of Mui Datatable to Enhance User Experience with Repeatable Edit and Delete

Hey Everyone, I'm currently trying to implement edit and delete buttons in ReactJS using Mui Datatable. However, I am facing a recurring issue due to the Map function since I am relatively new to ReactJS. Below is my image and code snippet: Here is a ...

Challenges with handling JSON data in JavaScript

I am currently attempting to retrieve and parse JSON data in order to display it on a blank HTML file. Unfortunately, I keep encountering an issue where if I retrieve and parse the data, I receive an error stating Uncaught TypeError: Cannot read property & ...

Bootstrap modal's offset returning blank value

One way to navigate to a specific element within a Bootstrap modal is by checking the offset of that particular element. If there are multiple divs within the modal, each with its own unique id (#row-1, #row-2, etc.), you can open the modal and input the f ...

The AngularJS $filter(date) function is causing incorrect format outputs

Hey there! I've come across an issue with my AngularJS filter, where it's supposed to return a date in a specific format. However, when I try the following code: var input = '2015-08-11T13:00:00'; var format = 'yyyy MMM dd - hh:mm ...

Ways to extract data from an array nested within a JSON object

I am seeking guidance on how to access the value of "result 2" from my JSON object using jQuery or pure JavaScript. var jsonarray = [{ title: "Category1", items: [{ result: "Item1", //Nested array items2: [{ //How to get the value o ...

Utilize Angular 2 to search and filter information within a component by inputting a search term from another component

In my application, I have a Component named task-board which contains a table as shown below: <tr *ngFor="let task of tasks | taskFilter: searchText" > <td>{{ task.taskName }}</td> <td>{{ task.location }}</td> <td>{{ ta ...

Create an Array of Objects by Sharing Your Post

Can someone guide me on the correct way to post my data here? I have been encountering errors while trying to insert data into user.SavedMachines.Id and user.SavedMachines.Date. I attempted using user.SavedMachines.Id = req.body.SavedMachinesId and user. ...

Prevent duplicate key errors when performing bulk insert operations with MongoDB

Is there a way to perform a bulk insert and proceed even if a duplicate key error occurs? I have a collection with a unique index on the id field (not _id) and some existing data. I need to add new data to the collection while skipping any documents that ...

Having trouble getting the if statement to run with JavaScript Closures?

Check out this code snippet: let url = URL; let imageURL = ''; $.getJSON("https://graph.facebook.com/?id="+encodeURIComponent(url)+"&scrape=true&method=post", function (data) { let json_data = JSON.stringify(data); json_data ...

Caution: React alert for utilizing the UNSAFE_componentWillReceiveProps in strict mode

As a newcomer to React, I encountered a warning that has me stuck. Despite researching extensively online, I still can't resolve it. The warning message is: https://i.stack.imgur.com/4yNsc.png Here are the relevant portions of the code in App.tsx: ...

Browser Compatibility in Three.js

Could someone assist me with activating webgl on Internet Explorer version 8? I am able to use Firefox and Chrome without any issues. Your help would be greatly appreciated. ...

PNG file is not displayed on React TSX page despite absence of any errors

I've implemented this initial design template from GitHub (https://github.com/vikpe/react-webpack-typescript-starter). Additionally, I'm utilizing react-bootstrap and have a container that includes a backgroundImage. const heroImage = require(&q ...

When external API validation fails, the JavaScript form is submitted

I am working on implementing form validation using an external email validation API. Below is the form tag I am using: <form class="form-horizontal" role="form" onsubmit="return validateForm()" method="post"> Here is a snippet of my JavaScript co ...

Retrieving the value of a formControl within a formArray is made possible through a reactive form in

How can I retrieve the value of ItemName in my HTML code? When I attempt to use {{invoiceForm.controls[i].items.controls.itemName.value | json}}, it returns as undefined. <form [formGroup]="invoiceForm"> <div formArrayName="items" *ngFor="let ...

Switching between components in Vue.js

I am a beginner with vue.js and I have encountered a challenge. On my page, I display a list of people with an 'Edit' button next to each person's details. My goal is to switch to another page when the Edit button is clicked, where I can edi ...