Can you tell me what a promise is?
Answer
In JavaScript, a promise is an object that represents the eventual completion or failure of an asynchronous operation and its resulting value. It allows for asynchronous code to be written in a more synchronous style, avoiding callback hell.
A promise can be in one of three states:
- Pending: The initial state of a promise, before it is resolved or rejected.
- Resolved: The state of a promise when it has been successfully resolved with a value.
- Rejected: The state of a promise when it has been rejected with a reason (an error object).
Here's an example of how to create and use a promise in JavaScript:
const myPromise = new Promise((resolve, reject) => { setTimeout(() => { const randomNumber = Math.random(); if (randomNumber >= 0.5) { resolve(randomNumber); } else { reject(new Error('Number is less than 0.5')); } }, 1000); }); myPromise.then(result => { console.log(result); }).catch(error => { console.error(error); });
In this example, a promise is created using the Promise
constructor, which takes a function as an argument. The function is passed two arguments, resolve
and reject
, which are functions that are used to either resolve or reject the promise. In this case, a random number is generated and if it is greater than or equal to 0.5, the promise is resolved with the number as its value. Otherwise, the promise is rejected with an error object.
The then()
method is used to handle the resolved value of the promise, and the catch()
method is used to handle any errors that may occur during the asynchronous operation.
Related JavaScript job interview questions
How are the 'async' and 'await' keywords used in JavaScript?
JavaScript JuniorWhat is 'this' keyword in JavaScript?
JavaScript JuniorCan you name two programming paradigms important for JavaScript app developers?
JavaScript JuniorWhat is functional programming?
JavaScript MediorWhat is the difference between classical inheritance and prototypal inheritance?
JavaScript Medior