Is it possible for promises to be executed in a non-sequential order in JavaScript

Consider the following code snippet:

const someAsyncFunc = async (num) => {
  console.log(num);
}

someAsyncFunc(123);
someAsyncFunc(234);

Could it be possible for 234 to be printed before 123? When invoking one async function before another, is there a guarantee that the first function will start executing before the second one? Should I always assume that any promise might experience an indefinite delay before execution, or is there a specific time frame within which it will begin executing?

Answer №1

Absolutely, it is a sure thing. In reality, `async` functions run synchronously until encountering the first `await`. Things get even more intriguing when we introduce an additional `await`:

const anotherAsyncFunc = async (num) => {
   console.log(`prior to ${num}`);
   await Promise.resolve();
   console.log(`subsequent to ${num}`);
};

  anotherAsyncFunc(1);
  anotherAsyncFunc(2);

The end result will be "preceding 1, preceding 2, subsequent to 1, subsequent to 2". This sequencing remains constant, as the duty of resuming function execution is placed in a task queue (immediately upon Promise resolution), ensuring the order's consistency.

If you were to `await` two Promises set to resolve at distinct future points in time, then the order could potentially vary.

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

Dealing with problematic JSON data in Google Apps Script

Struggling to extract the "oid" value from a JSON response using Google script for the first time. The original parsed JSON response is as follows: {btcs=0.01000000, orders=[{amount=0.10000000, price=2000.00000000, oid=592589, type=1}], plns=0.00440603} ...

How can I incorporate the "onClick()" function within an ajax call, while still utilizing the data returned in the success message?

After successfully making an Ajax call, I would like to implement an on-click function while still utilizing the original data retrieved. $.ajax({ URL: ......, type: 'GET', success: function (res) { var Ob ...

Tips for displaying a view with data fetched from various sources

I'm currently working on a project using backbone.js and I've encountered an issue with a model that doesn't need to synchronize with the server. This particular model is only meant to fetch user data for initializing other views; it acts as ...

Retrieve only the initial tag content using jquery

My goal is to extract the "22" from the following code... <div class="left"> <a class="count-link" href="http://url1.com"> <span>22</span> users </a> <a class="count-link" href="http://url2.com"> <span>10</span ...

The AngularJS $http.post method mimicking a successful $.ajax request is causing a 401 UNAUTHORISED error

I have been working on rewriting a functional $.ajax server call to utilize AngularJS $http.put. However, the $http method returns a 401 unauthorized error. The original ajax call I am attempting to rewrite is structured like this: $.ajax({ url: domain ...

The proper way to implement global scripts in Next.js

I am currently working on implementing a global fade-in animation for all components in my application. By adding the className "fadeIn" to each element and setting the default opacity to 0, I then utilize JavaScript to change it to 1 when the element is v ...

Ensure the header remains in a fixed position while scrolling in an Angular/Ionic app

Currently, users with limited screen space in my application encounter this when they attempt to scroll down: https://i.sstatic.net/Br0Wq.png What I actually want is for the header items What are you looking for? and Current location to remain fixed: ht ...

Having trouble retrieving information from an external local json file

I'm attempting to display an 'alert' box containing text retrieved from a JSON file. However, I'm facing issues in fetching data from the JSON file and the alert box is not being displayed. var thebook = JSON.parse(book); function s ...

The triggering of mouse events on 3D spheres in THREE.js does not occur accurately in the specified location

I've taken over a project from someone else and it's actually pretty cool. The goal is to create a dynamic diagram with nodes (spheres) that can be clicked on to reveal related nodes in a new diagram. Right now, I'm focusing on the clickabl ...

Resolver for nested TypeORM Apollo queries

I've set up a schema that includes database tables and entity classes as shown below: type User { id: Int! phoneNumber: String! } type Event { id: Int! host: User } Now, I'm attempting to create a query using Apollo like this ...

Having trouble with the "next" pagination button not loading cards, even though the numbered buttons are working perfectly

My pagination numbers are functioning correctly, but I'm having trouble with my "next" or "previous" buttons. I am using Bootstrap 5 and jQuery to load cards from an array. The issue seems to be with the currentPage variable in my displayList function ...

Develop a JavaScript function to declare variables

I am currently attempting to develop a small memory game where the time is multiplied by the number of moves made by the player. Upon completion of all pairs, a JavaScript function is executed: function finish() { stopCount(); var cnt1 = $("#cou ...

A guide on submitting form data containing an array to an API while utilizing Joi for array validation

For my Hapi API, I have set it up to only accept multipart/form-data. This is necessary because I need to include an image stream, and one of the payloads must be in the form of an array. To validate this, I am using Joi.array. payload: { parse: tru ...

Transforming a static array into a $http function response

I am currently attempting to switch my service from using a hard coded static array to an array retrieved from a $http call. Despite my efforts, the implementation is not functioning as expected. It is worth noting that the data returned from the http req ...

Is it possible to manipulate the carousel image within the div element?

I am working on a Bootstrap code snippet that showcases an image using the w-100 class to span the full width of the page. However, the challenge I'm facing is making sure the image is visible to users while keeping it small enough so they won't ...

Initiate Action Upon Visibility

After discovering this script that creates a counting effect for numbers, I realized it starts animating as soon as the page loads. While I appreciate its functionality, I would prefer it to only initiate when the element is in view; otherwise, the animati ...

What is the best way to transfer the date from one input field to another input field?

I have a requirement to automate the generation of an end date that is 3 months later when a start date is selected using jQuery. <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384 ...

401 Unauthorized response returned upon making a POST request in Angular due to token invalidation

Looking for assistance on understanding and implementing the process of adding a product to the cart upon button click. I have a list of products retrieved from an API, each with options to increment quantity using + and - buttons. When the + button is cli ...

Troubleshooting Problems with the Javascript Array Constructor

One question I have is why it's not recommended to declare an array like this: var arr = new Array() I always thought that declaring with [] was safer in case of accidentally overwriting the Array object, but... Array = 1; var arr = [] // boom ...

Reposition the parsley-errors-list within parsleyjs for improved functionality

I have implemented form validation using parsleyjs.org. Upon encountering a validation error, the plugin generates a ui.parsley-errors-list near the input field. The issue is that this .parsley-errors-list disrupts the layout by appearing right after the ...