DEV Community

Tufail Shah
Tufail Shah

Posted on

Chain some Math with Promises

This is a very simple and effective example on understanding promises, and how to pass in the arguments to it.

Image description

I keep on scribbling code on my handles, if you are interested give me a Follow:
Dev.to
LinkedIn
Css Battle
Code Sandbox

Input a number, double it, increase it by 10, and then multiply by 3.

Each operation should be in a separate Promise and then chained together.* */


double(value)
  .then(addTen)
  .then(multiplyByThree)
  .then((result) => {
    console.log(result);
  });
Enter fullscreen mode Exit fullscreen mode

Expected output:
60

Write functions which return promise object and resolve those.

  1. double return => x * 2
  2. addTen return => x + 10
  3. multiplyByThree => x * 3

Check the solution on JS Fiddle or

Down Below




const value = 5;

const double = (value) => new Promise((resolve) => resolve(value * 2));

const addTen = (value) => new Promise((resolve) => resolve(value + 10));

const multiplyByThree = (value) => new Promise((resolve) => resolve(value * 3));

double(value)
  .then(addTen)
  .then(multiplyByThree)
  .then((result) => {
    console.log(result);
  });
Enter fullscreen mode Exit fullscreen mode

Top comments (0)