Can an asynchronous function potentially return an object with a "then" function included?

When using the JavaScript async function (or a regular function that returns a Promise), any object with a function containing a "then" field is considered a Promise. However, is it possible to have such an object be the resolved value of a Promise?

For example, when calling the function await f(), no result is returned. If the field name in then is different, then a result is actually returned.


async function f() {
    return {
        then() {
            //This function simply has a fitting name as "then".
            return 42;
        }
    };
}

async function main() {
    let result = await f(); // execution stops here.
    console.log(result);
    console.log(result.then());
}
main();

Answer โ„–1

Upon delving into the information provided by await, a noticeable pattern emerges

await expression

expression

An object of type Promise, a thenable entity, or any value poised for anticipation.

Further exploration in the realm of thenable brings to light that

A thenable boasts an implementation of the .then() functionality

and

To facilitate seamless integration with prevailing Promise structures, the programming language sanctions the utilization of thenables instead of promises.

Hence, when employing await and furnishing an item furnished with a then capability, it signals to the JavaScript engine that this is indicative of a thenable object. Consequently, it expects said object to adhere to the prescribed thenable protocol.

Answer โ„–2

When working with an async function, it will always return a Promise. This means that you are essentially returning a Promise which in turn returns an object with a .then method. However, a proper .then method requires two arguments, both of which should be functions - onFulfilled and onRejected. Therefore, your current implementation of the then function is not considered a valid Promise.

A more effective approach would look something like this:

async function f() {
    return {
        then(onFulfilled, onRejected) {
            onFulfilled(42);
        }
    };
}
async function main() {
    let result = await f();
    console.log(result);
    f().then(result => console.log(result));
}
main();

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

Difficulty with Angular JS` ng-repeat functionality

I attempted to create a sample similar to the ones found on https://angularjs.org/ Here is the JS fiddle I put together. Could someone provide assistance? What seems to be the issue? The HTML code is as follows: <h2> To Do </h2> <div ng- ...

Tips for executing a series of tasks before a node js process is terminated

Dealing with signal from an external file in a JavaScript file. I have a shell script that stops all running processes. When my node process is stopped or killed, I need to perform a specific task before allowing the node to stop/killed. In my JavaScript ...

Merging Related Objects into a Single Object Array (JavaScript)

I have extracted user and permission data from my database and now I want to merge the access object with each user object so that I can easily access all the necessary information when displaying user permissions on a page in my application. Luckily, the ...

Making AJAX calls without displaying any alerts or prompts

I'm utilizing the $.when().then(success, fail).always() pattern to manage 3 asynchronous ajax calls. Here is the code I am using: $.when( $.ajax({ url: NewsCategoryUrl, beforeSend: function () { //alert('NewsCate ...

Refining a selection from a list using a multi-choice array

I have a filtering component that filters a list of people based on multiple input values. The string-based inputs filter properly, but when I select more than one item in the multi-select, nothing is displayed. This is likely due to person.role not contai ...

What is the method for transferring the value of a jQuery variable to a PHP variable without using AJAX?

Here is my JavaScript code: $('#affiliates_name').change(function(){ var id = $('#affiliates_name').val(); }); Below is the corresponding HTML: <select id="affiliates_name" style="display: none;" name="affiliates_name"> < ...

Retrieving historical data from a MySQL database to display in a div element

My main page features a button that opens a popup. Upon closing the popup, a script is triggered to call a PHP file for selecting data from the database. This selected data is then appended to a specific div within the main page: if (win.closed !== false ...

Tips for automatically refreshing Node.js project while utilizing pm2

Working on Node.js with Express.js currently, whenever a modification is made in the router or app file, I find myself manually typing the command: pm2 reload id_project. Is there a way to set up pm2 for automatic project reloading upon file changes? ...

Incorporating a .png file for hover effects

I've been trying to set up a tooltip that displays a png image when I hover over a section of a CSS map. Unfortunately, my attempts thus far have been unsuccessful. Every time I try to insert the image, it either causes the tooltip to disappear entir ...

Is there a way to verify if the overflow of an element with a width of 100% has occurred?

Here is the structure I am working with: <div class="card"> <div class="container"> <slot /> </div> </div> The Card element has a fixed width of 33rem. The container within it spans 100% of ...

What is the best way to incorporate Vue.js component dependencies into a multi-page application (MPA

When working with a multiple page app, incorporating a component inside another component can be challenging, especially without using a build system. $ npm install sagalbot/vue-select <template> <div id="myApp"> <v-select :value.sy ...

What is the best method for finding a button with an empty class name?

To access the search button on this page, follow this link: . Despite trying dr.findElement(By.cssSelector("button.button.cw-icon")), I was unable to locate the button labeled "ๆœ็ดข". Any suggestions on how to successfully locate it? ...

Adding a Library to Your Project

Being a newcomer to importing libraries into personal projects, I am attempting to import the mathjs library package for the first time. (). However, I am running into the issue on my website where it says "math is undefined" when I try to use it. You c ...

When using the get function, the HTML text remains unchanged

In my game, I am encountering an issue where the score does not update within my get function every time the game is played. Instead, I keep receiving null property errors. Any assistance on resolving this would be highly appreciated. I attempted to inclu ...

Show informational pop-up when hovering over selected option

My goal is to create an information box that appears when a user hovers over a select option. For example: <select id = "sel"> <option value="sick leave">Sick leave</option> <option value="urgent leave">Urgent lea ...

When the user presses the enter key to submit data, the Ajax page reloads

I am facing an issue with a simple form for sending messages from one person to another using AJAX method POST to prevent page reload. The problem arises when the user hits [ENTER] in the field, causing the page to reload instead of the AJAX working as int ...

What is the best way to toggle the readonly attribute on an input within an ng-repeat row when a button is clicked?

Here is some HTML content: <!---- HTML Content ----> <div class="container-fluid" ng-app="myApp"><br> <div class="row" ng-controller="mainController"> <div class="col-md-12"> <div class="panel pa ...

What is the best way to calculate checksum and convert it to a 64-bit value using Javascript for handling extremely large files to avoid RAM overflow?

Question: What is the best method for generating a unique and consistent checksum across all browsers? Additionally, how can a SHA256/MD5 checksum string be converted to 64-bit? How can files be read without requiring excessive amounts of RAM when ...

Create a function within jQuery that triggers when an option in a select field is chosen

As I edit a podcast, I have encountered a situation where an option is being selected through PHP code. Now, I am looking to implement jQuery functionality for when the option is selected from the select field. I have searched through various questions an ...

Passing arguments from the command line to an npm script

The scripts section in my package.json is currently set up as follows: "scripts": { "start": "node ./script.js server" } This allows me to use npm start command to initiate the server. All working well so far. However, I ...