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
  • 1,633
  • 9
  • 41
  • 99

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
  • 166,183
  • 27
  • 198
  • 186
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
  • 671
  • 1
  • 6
  • 19