Methods that are static and defined within the Promise constructor

While examining the static methods of the Promise constructor, I noticed that there are two methods called resolve and reject:

console.log(Object.getOwnPropertyNames(Promise))
// Array(7) [ "all", "race", "reject", "resolve", "prototype", "length", "name" ]

I started wondering whether these resolve and reject methods are the same ones used as parameters in the executor function, or if they are separate entities altogether:

const myFirstPromise = new Promise((resolve, reject) => {
//   do something asynchronous which eventually calls either:
//
//   resolve(someValue); // fulfilled
//   or
//   reject("failure reason"); // rejected
});

The specification talks about Promise Resolve Functions and %Promise_resolve% intrinsic object known as Promise.resolve ( x ). Can someone clarify if these refer to the same thing?

Answer №1

When you view the contents displayed by console.log(), they are actually referring to the properties .resolve() and .reject() of the global JavaScript Promise object. These can be thought of as static methods within the Promise class.

Essentially, they allow for the creation of new Promise objects that are either resolved or rejected from the start:

const p1 = Promise.resolve(3);
console.log(await p1);
// 3

The parameters resolve and reject that you use in your function call:

const myFirstPromise = new Promise((resolve, reject) => {
   if (rand() < 0.5) {
       resolve(3);
   } else {
       reject(new Error('not today'));
   }
});

are simply variables within the function itself and do not have any direct connection to Promise.resolve() and Promise.reject().

You could alternatively write the code like this:

const f1 = (resolve, reject) => {
   if (rand() < 0.5) {
       resolve(3);
   } else {
       reject(new Error('not today'));
   }
};

const myFirstPromise = new Promise(f1);

In this format, it becomes clearer that resolve and reject are local variables within function f1 and are independent of myFirstPromise or any other instances of Promise.

Answer №2

Utilizing Promise.resolve serves as a quick solution for "taking a value or a promise and enclosing it within another promise". By using

myPromise = Promise.resolve("myVal")
, you can achieve the same outcome in a more concise manner.

myPromise = new Promise((resolve) => resolve("myVal"))

The functionality of Promise.reject mirrors that of Promise.resolve, but instead of resolving, it explicitly rejects the promise.

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

What's up with the Chrome Dev Tools Error Log?

I am having an issue with debugging JavaScript files using breakpoints in Chrome Dev Tools. Whenever an error occurs, a red error message flashes on the screen so quickly that I can't read what it says. Is there a way to change this setting or access ...

Choosing a single random key-value pair from a specific attribute within a JSON schema

Is there a way to generate a new JSON schema based on the existing one, but with only one key-value pair chosen randomly from the "properties" attribute? The new schema should retain the "title" and "type" attributes as well. { "title": "animals object" ...

Issues arise when attempting to determine the accurate dimensions of a canvas

Looking at my canvas element: <canvas id='arena'></canvas> This Element is set to fill the entire website window. It's contained within a div Element, both of which are set to 100% size. I attempted running this script: var c ...

Learn how to create an endless scrolling effect on a static webpage using only pure JavaScript

Looking to achieve an Infinite Page Scroll Effect similar to Twitter without relying on jQuery or any other library, using pure JavaScript. I'm new to JavaScript and need assistance with implementing this effect in search results displayed within a La ...

Ensuring thoroughness in validation without the use of specific text strings

Implementing the assignment or assertion of never at the end of a function is a strategy commonly used in Typescript to ensure exhaustive checks at compile time. To enable the compiler to recognize this, explicit strings are needed for it to check against ...

The 404 error is handled by the express application before continuing to other routes. Some routes may not be recognized by the express.Router module

Shown below is the content of app.js: var express = require('express'); var routes = require('./routes/index'); app = express(); app.use('/', routes); // catch 404 and forward to error handler app.use(function(req, res, next ...

Text that changes within a set-sized box

I'm working with a fixed-size div that contains dynamically generated text. Is there an easy method using DOJO or plain Javascript to truncate the text before the end of the div and add "..."? How can I accomplish this regardless of the font size bein ...

What is the best way to delay Angular for 5 seconds before initiating a page transition?

Just a quick inquiry - is there a way to have Angular wait for 5 seconds before redirecting to a different page? I attempted to implement this functionality within my function, but it doesn't appear to be functioning as expected: setTimeout(() => ...

Using ngFor in Angular 6 to create a table with rowspan functionality

Check out this functional code snippet Desire for the table layout: <table class="table table-bordered "> <thead> <tr id="first"> <th id="table-header"> <font color="white">No.</font> </th> <th id="table-hea ...

Ways to launch the React Material date picker while hiding the date input field

I am working with the react material (MUI-X) date picker and my specific requirement is to have the date picker open on button click without displaying the date text field. I simply want to show the calendar and allow users to select a date. I have explore ...

Disable a button during an AJAX request

Whenever a button is clicked, the record is saved to the database without refreshing the page using AJAX. I have implemented the AJAX code successfully. Now I need guidance on how to manage the state of the Submit button - enabling/disabling it dynamicall ...

Why don't I need to include an onload event to execute the setInterval() method within the script tag?

Hey there! I'm diving into the world of Javascript and I've come across this interesting code that changes an image every four seconds. Surprisingly, it's working perfectly fine even though I didn't include an onload event to execute th ...

Exploring the Uses of SystemJS with TypeScript Loader

Can someone help clarify something about this TypeScript plugin for SystemJS? https://github.com/frankwallis/plugin-typescript/ Here is what the plugin does: This SystemJS plugin allows you to import TypeScript files directly and have them compiled in ...

Tips for successfully using JSON data in AJAX requests to PHP servers

I am currently working on a project involving a shopping cart. My task is to pass an array of objects that have been added to the shopping cart and stored in localStorage over to a PHP page for database insertion. console.log(localStorage.getItem("shoppin ...

EJS: Dynamically linking CSS and JS files according to specific page conditions

Is there a way to conditionally call CSS/JS files based on specific page conditions in EJS? Can we use a flag from the router or base it on the URL in the EJS file? Note: The code below works perfectly when accessing the /editor page, but it will cause er ...

What is the best way to selectively adjust object parameters in unit testing?

In my module, I have an object with several parameters. I want to rewire only specific parameters of this object. Here is a snippet from my 'module.js' file: var obj = { param_A: 'valueA', param_B: 'valueB', param_C: &a ...

Ways to determine if an AngularJS modal is currently displayed

I am currently in the process of determining whether a modal is opened or closed. However, I keep encountering an error that says "cannot read property of open." To address this issue, I realize that I need to connect with $modal.open and retrieve the resu ...

Incorporate a collection of product titles along with their short forms in JavaScript/jQuery

Seeking guidance as a newcomer to JS. I have encountered the need for two different views in an application I am working on - one displaying full product names and the other showing only their abbreviations. Instead of hard-coding this information, I wish ...

Limit pasted content in an Angular contenteditable div

Is there a way to limit the input in a contenteditable div? I am developing my own WYSIWYG editor and want to prevent users from pasting content from external websites and copying styles. I want to achieve the same effect as if the content was pasted into ...

React Application Issue: Unable to successfully redirect to the homepage upon logging in

Attempting to create a web application with the MERN stack is causing some trouble when trying to redirect users to the home page post-login. Here's how it should ideally function: User inputs login details The server validates these details and gene ...