Last active
October 29, 2017 08:51
-
-
Save kosinix/d401577953bd97a1e57d5ca7626b811d to your computer and use it in GitHub Desktop.
JS promise API gotchas
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function errorFunction(){ | |
return Promise.reject('Reject value.'); | |
} | |
function goodFunction(error=false){ | |
return Promise.resolve('Resolved value.'); | |
} | |
// Example 1. One level | |
goodFunction().then(function(ok){ | |
console.log('First "then" called. Value: ', ok); | |
}).catch(function(err){ | |
console.log('Outer "catch" called. Value: ', err); | |
}); | |
errorFunction().then(function(ok){ | |
console.log('First "then" called. Value: ', ok); | |
}).catch(function(err){ | |
console.log('Outer "catch" called. Value: ', err); | |
}); | |
// Example 2. Nested promises | |
goodFunction().then(function(ok){ | |
console.log('First "then" called. Value: ', ok); | |
// On ok, then is called | |
goodFunction().then(function(ok){ | |
console.log('Inner "then" called. Value: ', ok); | |
}).catch(function(err){ | |
console.log('Inner "catch" called. Value: ', err); | |
}); | |
// On error, catch is called | |
errorFunction().then(function(ok){ | |
console.log('Inner "then" called. Value: ', ok); | |
}).catch(function(err){ | |
console.log('Inner "catch" called. Value: ', err); | |
}); | |
}).catch(function(err){ | |
console.log('Outer "catch" called. Value: ', err); | |
}); | |
// Example 3. Nested promises not returned | |
goodFunction().then(function(ok){ | |
console.log('First "then" called. Value: ', ok); | |
// No return but the other then is executed with value undefined | |
goodFunction(); | |
}).then(function(ok){ | |
console.log('Outer "then" called. Value: ', ok); | |
}).catch(function(err){ | |
console.log('Outer "catch" called. Value: ', err); | |
}); | |
// Example 4. Nested promises returned | |
goodFunction().then(function(ok){ | |
console.log('First "then" called. Value: ', ok); | |
// Has return, the other then is executed with value of goodFunction | |
return goodFunction(); | |
}).then(function(ok){ | |
console.log('Outer "then" called. Value: ', ok); | |
}).catch(function(err){ | |
console.log('Outer "catch" called. Value: ', err); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment