1.Cleaner code and avoid callback hell
Using callbacks:
1 | function get(url, callback) { |
Using promises:
1 | // Wrap the request in a promise |
2.Backbones of some new features
Many APIs are promise-based:
- Fetch API
- MediaDevices API
- RTCPeerConnection
- Async functions
- Element API: requestFullscreen
- Document API: exitFullscreen
- HTMLMediaElement API: play
- OfflineAudioContext API: startRendering
- BaseAudioContext API: decodeAudioData
3.Automatic error handling
Using callbacks:
1 | get('./file1.txt', function(error, text) { |
Using promises, errors will be passed down the chain, so we can handle it in one common place without having to write it twice.
1 | let text1 = ''; |