Middle
List the static methods of Promise and explain what a promise is.
sobes.tech AI
Answer from AI
Promise is an object in JavaScript that represents the result of an asynchronous operation and can be in one of three states: pending, fulfilled, or rejected. It allows for more convenient handling of asynchronous code, avoiding "callback hell".
Static methods of Promise:
Promise.resolve(value)— creates a promise that is immediately fulfilled with the given value.Promise.reject(reason)— creates a promise that is immediately rejected with the given reason.Promise.all(iterable)— returns a promise that fulfills when all promises in the iterable are fulfilled, or rejects if any promise is rejected.Promise.race(iterable)— returns a promise that fulfills or rejects as soon as the first promise in the iterable fulfills or rejects.Promise.allSettled(iterable)— returns a promise that fulfills when all promises in the iterable have settled (fulfilled or rejected), with an array of results.Promise.any(iterable)— returns a promise that fulfills as soon as any promise in the iterable fulfills, or rejects if all are rejected.
Example usage:
Promise.all([fetch(url1), fetch(url2)])
.then(([res1, res2]) => {
// handle results
})
.catch(error => {
// handle error
});