"Pausing execution of a synchronous function by using Promise.all in JavaScript to wait for multiple promises to

Currently, I have numerous synchronous functions that need to run one after the other, and these are basic ajax requests responsible for rendering HTML content to the DOM.

My goal is to execute all of these synchronous functions asynchronously at the same time, allowing them to complete before moving on to speed up the process. However, within a synchronous function, attempting this in JavaScript seems challenging, so I am seeking advice from the community.

My approach involved converting each synchronous request into asynchronous promises and then using a Promise.all() method to handle them. Nevertheless, waiting for promise.all().then is not ideal as the main thread will continue executing the remaining code in the synchronous function. Therefore, I'm looking for a way to halt the main thread until the asynchronous calls are completed.

Here's a brief example of what I'm facing:

var syncfunc = () => {
    var getPromise = () => {
        return new Promise((resolve) => {
            var asyncAjaxRequest = async function() {
                doSomeStuff();
                resolve();
            }
        })
    }

    var promises = [getPromse(), getPromse(), getPromse()];

    Promise.all(promises);

    console.log('I want this console.log to execute only after all promises have finished executing doSomeStuff');
}

While I understand that .then will trigger once all promises are resolved, my objective is basically to block the synchronous thread till all asynchronous tasks are completed.

If possible, I would restructure everything according to my needs, but due to utilizing the SiteVision framework, I'm trying to add content to the DOM before a print module opens the print window. Running each function synchronously isn't efficient as it slows down the process. Disabling the print function by setting window.print = null and enabling it again upon resolution of promises didn't yield the desired results.

Answer №1

Converting an asynchronous operation into a synchronous one in plain Javascript is not possible without external code due to the way the event driven JS engine functions.

An asynchronous operation initiates the task by handing off execution to native code and then returns to the interpreter to continue executing the subsequent code. When the native code completes, it adds an event to the JS event queue allowing the interpreter's event loop to handle the asynchronous operation's completion. Creating a "block" like a semi-infinite while loop would prevent the interpreter from processing further code, leading to a deadlock situation where the loop waiting for the operation to finish prevents the interpreter from reaching the point necessary to process the end signal of the operation.

Because of the single-threaded event loop nature of the JS interpreter, blocking to wait for the completion of an asynchronous operation is not feasible solely in Javascript. The preferred approach is typically to adjust the surrounding code or infrastructure to accommodate asynchronous operations and results (via callbacks or promises).


In node.js, there are potential solutions that involve using hacky techniques to achieve a synchronous result, such as writing a custom nodejs plugin for blocking interfaces in native code or utilizing synchronous child_process operations to run code in a separate process and continue upon its completion.

However, these methods are generally considered poor practices and should be avoided as they inhibit the entire interpreter. Moving the asynchronous operation outside of Javascript or the current process is often necessary in order to implement blocking behavior.


If you're struggling to address your issue with non-blocking, asynchronous operations, consider posting a new question detailing your problem for assistance in designing an appropriate asynchronous solution. Feel free to provide a link to the new question in a comment here so others may offer their insights and aid in finding a resolution.

Answer №2

To tackle this issue, you can implement async/await. Here's how you can go about it:

async function handlePromises() {
    var createPromise = () => {
        return new Promise((resolve) => {
            var asyncRequest = async function() {
                performTasks();
                resolve();
            }
        })
    }
    
    var promiseArray = [createPromise(), createPromise(), createPromise()];
    
    await Promise.all(promiseArray);
    
    console.log('I wish for this console.log to run once all promises are completed and tasks are performed.');
    
    /**
     * 
     * Promise.all(promiseArray).then(() => {
            // I cannot use this method as it involves scripts in other files that will execute if I wait like this
        })
     */
}

In essence, your code waits until all promises in the array have been resolved before proceeding with execution. It is important to note that despite the synchronous nature of code execution, it remains non-blocking.

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

Tips on avoiding a page reload following a form submission using JQuery

Currently developing a website for my app development project, I've encountered an unusual issue. Utilizing some JQuery to transfer form data to a php page called 'process.php' and then add it to my database. The strange part is that the pa ...

Using the .val() function to retrieve values from a list in PHP

I am attempting to retrieve data from a list (listDIV) to display in my form (formDIV). The data is fetched from a database using JSON. However, I keep encountering the error "Database error, please select something else." in my textarea field, indicating ...

Dynamic Data Display

I'm experiencing an issue where the data is not displaying in the table div when using an Ajax call to load the table. The page appears blank upon return, and I have tried using $('#groupTable').load(data); without any success. If anyone can ...

Importance of asynchronous tasks in managing memory streams

Currently, I am working with a library in C# using mono 3.0 that utilizes a stream for serializing data, but does so synchronously. In order to create an asynchronous network library, I plan to provide a memory stream to the serializer and then send this s ...

Invoke the method only upon a human's input modification in Vue.js, rather than the method itself altering the input

Recently diving into Vue, I've been working on creating a form that triggers an API call whenever an input is changed. The main goal is to dynamically populate and set other inputs based on the user's selection of a vehicle. For example, when a ...

What is the best method for incorporating dynamic page transitions when navigating between individual pages?

Let's say I have the following pages: red.html blue.html green.html My goal is to create links from red.html to blue.html and red.html to green.html. When attempting to use page anchors and iframes, I encountered an issue where scrolling from red.h ...

"Troubleshooting Problems with Scaling in the jQuery Mouse Wheel Plugin

I am currently utilizing this code in conjunction with the following plugin: mouse wheel $('#painter').on('mousewheel', function(e) { cp.scale(2, 2); var e0 = e.originalEvent, delta = e0.wheelDelta || -e0.de ...

Can the Python yield feature be replicated in standalone C programming?

After discovering the yield keyword in Python and JavaScript, I found its use in asynchronous functions intriguing. While primarily used for the generator pattern, in asynchronous functions it acts as a form of syntactic sugar that I find appealing. Despit ...

issues with responsive mobile navigation

Greetings! I've been diligently working on a website project for a client, but I have a nagging feeling that I may have overlooked something important. If you'd like to take a look at the small design mockup preview I'm providing for the cl ...

Enhancing Angular 5 with CustomEvent Polyfill for JavaScript

After implementing the code snippet in main.ts file, I encountered an issue with CustomEvent not being added to the window object correctly. Strangely, when I manually add CustomEvent using the JavaScript console, it works fine. This problem arises specifi ...

The date range picker displays the previous arrow but not the next arrow

I am currently using the DateRangePicker tool and for some reason, I am not seeing the arrow that should appear on the right side. I have double-checked my configuration but can't seem to figure out what is causing this issue. In the image attached, ...

Fixing Typescript assignment error: "Error parsing module"

Trying to assign an object to the variable initialState, where the type of selectedActivity is Activity | undefined. After using the Nullish Coalescing operator (??), the type of emptyActivity becomes Activity. However, upon execution of this line, an err ...

``There seems to be a problem with the ngb time picker when using the up and

Currently, I am utilizing Bootstrap 4 and NG Bootstrap time picker for a project in Angular 10. Despite correctly adding all the code, I have encountered an issue where the up and down arrows on the time picker are not functioning as expected. Below is a s ...

Is it possible to conceal or disregard text elements from the web browser search function by using CTRL+F?

I have a complex web application interface with a dedicated area for content display. Is there a way to ensure that when users utilize the browser's text search function (CTRL+F), the UI elements are ignored and only the actual content is searched? ...

Guide to updating a Many-to-Many field in Django using an AJAX request

Creating a user profile in Django involves collecting information on the user's skill set. The skill field is connected to a model named Skills and is a ManyToMany field. Below is an example of how this connection can be set up in the models.py file: ...

The perfect method for creating template literals using a function

I have a function that accepts an argument called id and returns a template literal: const generateTemplate = (id) => { return `<div style="box-sizing: border-box; height: 32px; border-bottom: 1px solid #ECECEC; color: #282828; padding: 8px; dis ...

Using an AJAX post request to retrieve the HTML content

I'm grappling with an AJAX function and a processor.php script. Here's the code snippet: $.ajax({ url: "processor.php", type:"POST", data: { 'id' : "itemid, 'itemname' : itemname, 'itemdesc' : itemdesc" ...

Exploring the use of Async/Await in Node.js 8 with Mongoose

Currently, I am using nodejs version v8.5.0 with nvm. In my project, there is a simple index function that retrieves all users from the MongoDB database using mongoose. User.find({}, (err, results) => { if (err) { return res.json(err); ...

What could be the reason for the child event not updating the state in the parent component (Vue)?

I have a component called customize-charts which contains a Vuetify drawer: <template> <v-col> <v-btn style="float: right" class="mr-4 mt-2" small @click="toggleCustomize" v-if="!open">Custom ...

Retrieve data from TypeScript file (.ts) and use it in an HTML document

Recently I started learning Typescript and HTML as I work on building an Angular2 application. At the moment, I have a TypeScript file that resembles the following structure: import {Http, Headers} from 'angular2/http'; import {Component} from & ...