Fetch is the new Promise-based API for making network requests:
fetch(\'https://www.everythingisawesome.com/\')
.then(response => console.log(\'status:
After reading through the implementation of fetch, it seems that promises are used for a few reasons. For starters, json() relies on a FileReader to convert the response blob into text. FileReaders can't be used until the onload callback, so that's where the promise chain starts.
function fileReaderReady(reader) {
return new Promise(function(resolve, reject) {
reader.onload = function() {
resolve(reader.result)
}
reader.onerror = function() {
reject(reader.error)
}
})
}
From there, additional promises are used to encapsulate particular errors that might occur and propagating them up to the caller. For example, there are errors that can occur if the body has already be read once before, if the blob doesn't convert to text, and if the text doesn't convert to JSON. Promises are convenient here because any of these various errors will simply end up in the catch block of the caller.
So in conclusion, a promised based api is used for reading fetch responses because:
1. They rely on a FileReader which has to initialize itself asynchronously.
2. fetch would like to propagate a wide variety of errors that may occur in reading the body. Promises allow a uniform way to do this.