ES6 Promise-4
Use new Promise directly in .then without putting in callback
by Po-Jung Chen
JavaScript
/**
* Use new Promise directly in .then without putting in callback
**/
// EXAMPLE 1
function waitASecond(second) {
console.log(second)
return new Promise((resolve, reject) => {
setTimeout(function() {
second++
resolve(second)
}, 1000)
})
}
waitASecond(0)
.then(waitASecond)
.then(waitASecond)
.then((second) => {
console.log(second)
})
// EXAMPLE2
const calculatePromise = new Promise((resolve, reject) => {
console.log('In new Promise, start callback')
setTimeout(() => {
let answer = 3 + 5
resolve(answer)
}, 1000)
})
function addTwo(value) {
console.log('current value', value)
return value + 2
}
function printResult(value) {
console.log('The final value is ' + value)
}
calculatePromise.then(addTwo)
.then(addTwo)
.then(printResult)