A Promise in JavaScript is an object that links “Producing Code” (code that takes time, like loading data) and “consuming code” (code that wants the result once it's ready). It allows you to handle asynchronous operations, such as fetching data from a server or reading a file, in a more manageable way.
let promise = new Promise(function(resolve, reject) {
// executor (the producing code)
});
The function passed to new Promise is called the executor. When new Promise is created, the executor runs automatically. It contains the producing code which should eventually produce the result. Inside the executor.
Its arguments resolve and reject are callbacks provided by JavaScript itself. Our code is only inside the executor.
When the executor obtains the result, be it soon or late, doesn’t matter, it should call one of these callbacks:
resolve(value) — if the job is finished successfully, with result value.reject(error) — if an error has occurred, error is the error object.The promise object returned by the new Promise constructor has these internal properties:
resolve is called.reject is called.resolve(value) is called.reject(error) is calledOnce a promise is created, you can consume it using .then() and .catch() methods.
The .then() method is used to handle both success and failure results. It takes two functions as arguments:
resolve(value) in the executor. It receives the value as an argument.reject(error) in the executor. It receives the error as an argument.promise.then(
function(result) { /* handle success */ },
function(error) { /* handle error */ }
);
If you're only interested in handling the successful result, you can omit the second function: