0

I was trying to learn how to avoid the anti pattern as described here What is the explicit promise construction antipattern and how do I avoid it?

I started with some code on JSFiddle but it does not output what I expected..

function sum1(x){
    return new Promise(resolve => x+1)
}

function sum2(x){
  return sum1(x)
  .then(x => x+1);
}

function sum3(x){
  return sum2(x)
  .then(x => x+1)
}

sum3(1)
.then(console.log);

I would expect it to print 4 but it prints nothing

Mojimi
  • 2,561
  • 9
  • 52
  • 116

2 Answers2

3

You need to create a resolved promise by using Promise.resolve():

function sum1(x){
    return Promise.resolve(x+1)
}

function sum2(x){
  return sum1(x)
  .then(x => x+1);
}

function sum3(x){
  return sum2(x)
  .then(x => x+1)
}

sum3(1)
.then(console.log);
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
2

you are doing it wrong in sum1. new Promise((resolve, reject) => {//code here}) takes function as argument

function sum1(x){
    return new Promise((resolve) => {
     resolve(x + 1);
    })
}

function sum2(x){
  return sum1(x)
  .then(x => x+1);
}

function sum3(x){
  return sum2(x)
  .then(x => x+1)
}

sum3(1)
.then(res => console.log(res));
Saad Mehmood
  • 691
  • 1
  • 7
  • 19