0
0
Node.jsframework~5 mins

Promises for cleaner async in Node.js

Choose your learning style9 modes available
Introduction

Promises help you handle tasks that take time, like loading data, without freezing your program. They make your code easier to read and manage when working with things that happen later.

When you want to load data from the internet without stopping other parts of your program.
When you need to wait for a file to be read before continuing.
When you want to run several tasks one after another, but only after the previous one finishes.
When you want to handle errors from asynchronous tasks in a clean way.
When you want to avoid deeply nested callbacks that are hard to read.
Syntax
Node.js
new Promise((resolve, reject) => {
  // Do some async work
  if (success) {
    resolve(result); // Task finished successfully
  } else {
    reject(error); // Task failed
  }
});

resolve is called when the task finishes well.

reject is called when something goes wrong.

Examples
This promise waits 1 second, then says it is done.
Node.js
const myPromise = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('Done!');
  }, 1000);
});
Here we say what to do when the promise finishes or fails.
Node.js
myPromise.then(result => {
  console.log(result);
}).catch(error => {
  console.error(error);
});
Using promises to get data from the internet and handle errors.
Node.js
fetch('https://api.example.com/data')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));
Sample Program

This program waits 1.5 seconds, prints a message, then waits 1 more second and prints another message. It uses promises to handle the waiting cleanly.

Node.js
function wait(ms) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(`Waited ${ms} milliseconds`);
    }, ms);
  });
}

wait(1500)
  .then(message => {
    console.log(message);
    return wait(1000);
  })
  .then(message => {
    console.log(message);
  })
  .catch(error => {
    console.error('Error:', error);
  });
OutputSuccess
Important Notes

Promises let you chain tasks with .then() for better flow.

Always add .catch() to handle errors and avoid crashes.

Promises make your code easier to read compared to nested callbacks.

Summary

Promises help manage tasks that take time without freezing your program.

Use resolve and reject to signal success or failure.

Chain .then() and .catch() to handle results and errors cleanly.