What is a Promise?
A Promise is an object in JavaScript that represents the eventual completion (or failure) of an asynchronous operation and its resulting value. It allows you to write asynchronous code in a more manageable and readable way by handling success and error cases.
Using Promises: Creating and Handling
You can create a custom Promise instance to handle asynchronous tasks. Once you have a Promise, there are two main ways to handle its result or error:
- Using
.then()
and.catch()
- Using
async/await
withtry/catch
Example:
function customPromise(condition) {
return new Promise((resolve, reject) => {
if (condition) {
resolve("Success");
} else {
reject("Failure");
}
});
}
Instead of new Promise ()
instance we can use async/await
, which acts the same.
Equivalent using async/await
:
async function customPromise(condition) {
if (condition) {
return "Success"; // resolves
} else {
throw "Failure"; // rejects
}
}
-
return
→ resolves the Promise -
throw
→ rejects the Promise
Handling promise with .then()
and .catch()
customPromise(true)
.then(result => console.log("Result:", result)) // If the Promise resolves, this block runs
.catch(error => console.error("Error:", error)); // If the Promise rejects, this block runs
Handling promise with async/await
and try/catch
async function handle() {
try {
const result = await customPromise(false); // If 'false', this will reject
console.log("Result:", result);
} catch (error) {
console.error("Error:", error); // This catches the rejection reason
}
}
handle();
Built-in Promises
Many modern JavaScript APIs return Promises by default. For example, the fetch
API used for network requests returns a Promise that resolves with the response object.
You can handle these Promises using the same techniques (async/await
or .then()
/.catch()
) without needing to create them yourself.
async function fetchData() {
try {
const response = await fetch("https://api.example.com/data");
const data = await response.json();
console.log(data);
} catch (error) {
console.error("Fetch error:", error);
}
}
fetchData();
Other built-in Promise-returning APIs include:
-
Response.json()
(parsing JSON from fetch response) -
fs.promises
methods in Node.js (readFile
,writeFile
, etc.) -
Promise.all()
,Promise.race()
,Promise.resolve()
,Promise.reject()
-
crypto.subtle
API (Web Crypto) -
cacheStorage
methods in Service Workers
Built-in Asynchronous Functions Without Promises
Some built-in asynchronous functions, like setTimeout
, execute tasks asynchronously but do not return Promises. Instead, they rely on callbacks to handle completion.
If you want to use them with Promises or async/await
, you need to wrap these functions manually in a Promise.
function delay(ms) {
return new Promise(resolve => {
setTimeout(resolve, ms);
});
}
async function run() {
await delay(1000);
console.log("Waited 1 second");
}
run();
Other built-in asynchronous functions that use callbacks but do not return Promises:
-
setInterval()
/clearTimeout()
/clearInterval()
navigator.geolocation.getCurrentPosition()
-
XMLHttpRequest
(older AJAX API) - Event listeners (
addEventListener
) - Node.js callback-based
fs
methods (fs.readFile
,fs.writeFile
, etc. without.promises
) -
process.nextTick()
andsetImmediate()
in Node.js
Top comments (0)