A JavaScript promise that triggers the "then" function right away

As I work on developing a single-page app, JavaScript promises have become a critical component. In specific scenarios, I require the "then" method to execute synchronously if the promise is already resolved. To address this need, I have created a custom promise implementation as a wrapper class, which serves its purpose effectively but hinders my ability to utilize async/await. Can both be used simultaneously considering async/await appears to be essentially just syntax sugar around "then?"

The custom promise implementation adheres to the PromiseLike TypeScript interface, yet it seems that async/await always requires a native promise. Why is this so?

I'm contemplating the idea of replacing the "then" method of an authentic promise object rather than constructing a wrapper on top of it. Will this approach yield the desired outcome?

The urgency for immediate execution of "then" stems from the fact that the culmination of the promise chain signifies a property within a React component. This React component exhibits a loading indicator until the promise resolves. Without my custom wrapper, the loading indicator flickers each time the component updates, disrupting user interaction.

Perhaps there exists an alternative solution to tackle this issue. This venture into the realm of JavaScript marks my maiden voyage.

In my development endeavors, I employ TypeScript and target ES6 standards.

Answer №1

It seems that async/await always requires a native promise.

Actually, it does not. The await keyword can be used on an object that has a .then method.

If my wrapper is not used, the loading indicator appears briefly every time the component updates, causing issues with user interaction.

This issue is not caused by waiting for resolved promises. The .then method is executed in a microtask, meaning that if the promise is already resolved, the .then will execute immediately after the engine completes its current task, before the browser re-renders.

let promise = Promise.resolve(1);

setTimeout(() => { // Ensure the promise is resolved
 console.log("sync");
 promise.then(() => console.log("then"));
 requestAnimationFrame(() => console.log("redraw"));
 console.log("sync end");
}, 1000);

You'll see sync, sync end, then, redraw in the console.

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

Displaying infowindow pop-ups on random markers on Google Maps every 3 seconds

Here lies the challenge. I am tasked with creating a Google map that displays multiple markers. Each marker must have a unique info window with distinct content. Upon opening the website, an info window randomly appears on one of the markers after 3 sec ...

Forced line break at particular point in text

I would love to implement a line break right before the "+" character, either using css styling or through a different method. Is this task achievable? #myDiv{ width: 80% } #myP{ c ...

Exploring the capabilities of utilizing Await/Async functions in Node.js

Here is my custom Axios Request function to make API calls. export function axiosGet (url) { return opsutils.get(url) .then(function (response) { return response.data.data; }) .catch(function (error) { return 'An error occu ...

What is the best way to show and hide the information in a FAQ section when each one is clicked?

const faqItems = document.getElementsByClassName("faq-question"); const faqContents = document.getElementsByClassName("faq-content"); for (item of faqItems) { console.log(item); item.addEventListene ...

Do developers typically define all flux action types within a constants object as a common programming practice?

This question arises from an informative article on flux. The common approach involves defining all action types within a constants object and consistently referencing this object throughout the application. Why is it considered a common practice? What ...

The issue arises when d3.scaleLinear returns NaN upon the second invocation

My journey with d3.js is just beginning and I'm taking it slow. Currently, I'm focused on creating a bar chart where data is loaded from a json file. When I click on the bars, the data changes to another column in the json. This is how my json f ...

What is preventing me from specifying a specific position in my multi-dimensional array?

My goal is to create a 3D version of an L-System, but I'm having trouble declaring elements in my multidimensional array. Even when I try to assign values to specific positions, the elements don't seem to update properly. For instance, if I write ...

Tips for utilizing the value of object1.property as a property for object2

Within the template of my angular component, I am attempting to accomplish the following: <div> {{object1.some_property.(get value from object2.property and use it here, as it is a property of object1)}} </div> Is there a way to achieve this ...

I can't seem to retrieve my email using the code provided. The second console statement is not displaying any information. Why might this be happening?

I've been struggling to retrieve the email entered in a form and print it in the console. Despite my code compiling without errors, the email is not being fetched. My goal is to utilize nodemailer for sending registration emails, but I'm encounte ...

Interactive Icon Feature Instead of Annoying Pop-Ups in JavaScript

Hello there! I need assistance fixing a code issue. Currently, the code automatically pops up when the page is opened. Is there a way to make it clickable instead of popping up automatically? <script type="text/javascript" src="//www.klaviyo.com/media/ ...

Enable the x-axis months to be interactive in a chart.js line graph

Currently, I am in the process of developing a line chart using chart.js. The x-axis of the chart is time-based and represents months. I want to make each "month column" clickable/selectable, but I'm facing difficulty in achieving this functionality ...

"Graphs not Displaying Properly in ChartJs

Seeking assistance with rendering a chart inside a bootstrap popover. Despite various debugging attempts, the chart refuses to render. Any help or insight would be greatly appreciated. Below is my HTML code: <div id="popover-content" style=&qu ...

PHP: Communicating Data with JavaScript

What if my PHP script requires some time to complete its operations? How can I keep the client updated on the progress of the operation, such as during a file download where the estimated time and data size need to be communicated? In PHP, calculating all ...

Using jQuery to serialize parameters for AJAX requests

I could use some help figuring out how to set up parameters for a $.ajax submission. Currently, I have multiple pairs of HTML inputs (i pairs): > <input type="hidden" value="31" name="product_id"> <input > type="hidden" value="3" name="qua ...

Issue with showing multiple images on HTML page

I'm currently working on enhancing my webpage by enabling the upload of multiple images. However, I'm facing challenges in figuring out how to obtain a valid URL for the image source and to verify if the correct number of files have been uploaded ...

Creating a regular expression variable in Mongoose: A step-by-step guide

I am looking for a solution to incorporate a variable pattern in mongoose: router.get('/search/:name', async(req, res) => { name = req.params.name; const products = await Product.find({ name: /.*name*/i }).limit(10); res.send(prod ...

Unbearably long wait for Ajax request

For some reason, my Javascript code is running incredibly slow, taking up to five minutes to complete. Sometimes after refreshing the page, certain requests haven't even been processed yet. I've already tried setting async:true, hoping it would ...

What is the best location for implementing role-based authentication in a MeanJS application?

I am working with a meanJS starter template that includes a yeoman generator. I'm trying to figure out where I can add specific permissions to my modules. For example, 'use strict'; // Configuring the Articles module angular.module(' ...

Jquery Ajax failing to retrieve a response

Here's the jQuery script I am using to fetch data from my server: $(".login_button").click(function () { var username = $(".username").val(); var userkey = $(".userkey").val(); $.ajax({ type: "GET", url: "http://192.168.0. ...

What is the reason behind the failure to update the state via a reducer and Object.assign?

I'm attempting to develop a reducer without utilizing ES6. It's an outmoded PHP application that lacks a build process for transpilation. I am initializing the state: let defaultState = { accountTypes: { individual: { c ...