Reputation: 3161
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
Upvotes: 0
Views: 38
Reputation: 191976
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);
Upvotes: 3
Reputation: 731
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));
Upvotes: 2