Is it possible for me to develop my own custom "then()" function in JavaScript and have it run successfully?

While familiarizing myself with Promises in Javascript through a tutorial, I noticed the use of the then() method in various instances.

Upon writing the code below, I stumbled upon the "then()" function within the __proto__ section of the console:

const myPromise = new Promise(function(resolve, reject) {});
console.log(myPromise);

However, when I wrote the following code for a car class, I did not see the "then()" function present:

class Car {
   constructor(color, type, doors) {
      this.color = color;
      this.type = type;
      this.doors = doors
   }
}
const myCar = new Car('blue', 'sedan', '4');
console.log(myCar);

This raised an intriguing question in my mind: Is it possible to create our own custom then() function in Javascript and run it?

Answer №1

Check out this insightful blog post. By the end, you'll have a comprehensive understanding of promises.

Answer №2

When you create a promise, its __proto__ points to Promise.prototype. On the other hand, when you create an object using a class, its __proto__ points to Object.prototype.

If you want more information on this topic, check out this link.

It is possible to create our own then function and execute it, but this should only be done if you fully understand what you are doing.

Here is an example of creating our own then method:


class MyObj extends Object {
  then() {
    console.log('The "then" method has been called');
  }
}

var mo = new MyObj();

You can now call mo.then().

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

Incorporating an additional HTML form to the webpage

I've written some code and I'm looking to add another medicine when the + button is clicked. How can I achieve this? <html> <body style="color:black; font-size:20px;"> <form> <label style="margin-right:95px ...

Error in Syntax & Function is Undefined

issues controllers.js:6 Uncaught SyntaxError: Unexpected token ( ionic.bundle.js:26794 Error: [ng:areq] Argument 'MenuCtrl' is not a function, got undefined In the process of developing a cross-platform app using Ionic framework with WordPress ...

Dealing with cross-origin AJAX posting in Node.js处理Node.js中的

My app.js contains the following handler for POST requests: app.all('/', function (req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "X-Requested-With"); next(); }); app.opt ...

Retrieving data using the GetJSON method consistently returns identical values

Here is the code I have written: $(document).ready(function () { $.getJSON("data.json", function (data) { var user_Data = ""; $.each(data, function (key, value) { user_Data += '<p class="user">' + value.na ...

Using ng-model to create association between a select box and ng-repeat to populate its options

Here is a Plunker link demonstrating my problem. I have an object that includes a division property. The issue is, there is no division_id in the object, but to set or update the division, I need to set the division_id field. Here's an example of the ...

What mechanisms does React use internally to detect changes within a component?

Is there a way for a component to recognize when its props have been modified so that it can trigger a re-render? For instance: function myComponent(props){ return <p>{this.props.data}</p> } function parent(){ let dataValue = 0; set ...

How can I extract data from an XML file and include it in a JSON file using GulpJS?

Being relatively inexperienced with Gulp/Node programming, I am facing some difficulties while trying to accomplish a simple task :) Within my XML file, there exists a node like the following: <widget version="1.1"></widget> My goal is to ext ...

Differences Between JSON.parse() and .json()There are distinct variations between

Recently, I've been diving into using fetch API and Promises, which led me to .json(). It's interesting how often .json() gives the same result as JSON.parse. After some initial confusion, I turned to Google for answers, only to be redirected in ...

JavaScript - Ways to retrieve the date in the desired format

Looking to display the Date output in 2 different formats. Below is my current attempt: <p id="demo"></p> <script> var d = new Date(day, month); document.getElementById("demo").innerHTML = d.toString(); </script> Unfortunately, t ...

How can we implement :focus-within styling on Material-UI Select when the input is clicked?

I am currently implementing a Select component inside a div element: <div className="custom-filter custom-filter-data"> <DateRangeIcon className="search-icon"/> <FormControl variant='standard& ...

Start an HTML5 video inside an iframe by clicking on the play button on the parent page

My web page features a video in an iframe that can be changed by clicking on links within the page. I have added play and pause buttons on the main page to control playback of the videos within the iframe. On another page without an iframe, I successfully ...

Shifting Icon to the Right within the Drawer Navigator Toolbar

While modifying the example code for Material UI's drawer navigator, I decided to enhance it by adding a notification icon and a checkout icon with the Admin Panel typography in the toolbar. However, I encountered an issue where the checkout icon app ...

Increase initial zoom for React Three Fiber OrbitControls to provide a wider view

I've been working on a project in React Three Fiber using this codesandbox for practice. My query regarding the demo is about setting a wider initial zoom in OrbitControls to view more small stars. Can anyone help with this? Below is the code snippe ...

I'm only appending the final element to the JavaScript array

Currently, I have the following code: I'm endeavoring to create a new JSON object named dataJSON by utilizing properties from the GAJSON object. However, my issue arises when attempting to iterate over the GAJSOn object; only its last element is added ...

File or directory does not exist: ENOENT error encountered when attempting to access 'distrowserindex.html'

Upon executing ng deploy --preview, an error is encountered: Error: ENOENT: no such file or directory, open 'dist\index.html' at Object.openSync (fs.js:457:3) at readFileSync (fs.js:359:35) Despite attempting various online tutorial ...

JS roles encountered an issue with a TypeError: it is unable to read the property 'push' because it is undefined

I'm experiencing a problem with setting roles in the admin panel of my website. The roles I've configured are mmUser, mmMerchant, mmAdmin. When a user signs up, they are automatically assigned the mmUser role. In the admin panel, I'm attemp ...

Imitate a hover effect

In my list, I have images and descriptions set up in the following format: <li> <img class="photography" src="PHOTO/boat.jpg" alt="Boat on sea." /> </li> <li><div id="description" class="description"> <p>BOAT</p> ...

The try and catch block in JavaScript is failing to correctly capture the HTTP status

I have a function that successfully posts JSON to an API endpoint. Here is the code I am using: function sendValuesPageLoad(){ var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function () { try { if (xhr.readyState === ...

Continue iterating through the range of dates until the first date comes before the second date

I have a pair of Unix timestamps: let start: number = 1632988953; const end: number = 1638259353; My goal is to iterate over these two dates, recalculating the new start date in each iteration. To achieve this, I am utilizing a while loop as shown below ...

Use middleware for multiple routes with just one call

I have an API for a dashboard which includes routes such as: /dashboardRoutes/getdata1 /dashboardRoutes/getdata2 . . . /dashboardRoutes/getdata7 On the backend, I am using express router.use to direct these routes to a handler. router.use('/dashboard ...