It's really important to note that the Promise object doesn't return a value, it resolves a value via the then() method.
It is the fetch() function that returns a value, which is a Promise instance.
It is the Promise instance on which you call the then() method, passing in a callback function, which will be eventually be fired when the async code finishes (and internally, calls resolve()).
As an example, here's what a custom load function might look like:
functionload(url){returnnewPromise(asyncfunction(resolve,reject){// do async thingconstres=awaitfetch(url)// your custom codeconsole.log('Yay! Loaded:',url)// resolveresolve(res.json())// see note below!})}// run the function and receive a Promiseconstpromise=load('https://...')// let the Promise know what you want to do when it resolvespromise.then(console.log)
Note that the Promise object will resolve any nested promises as part of its work, so resolving res.json() which results in a Promise being created will be resolved internally before the final chained .then(console.log) is called.
The trick to Promises is:
always return Promises you create (or functions that return Promises) so they can be chained
always resolve() or reject() within the promise executor so .then() or .catch() will be called and the chaining will complete
It's really important to note that the
Promise
object doesn't return a value, it resolves a value via thethen()
method.It is the
fetch()
function that returns a value, which is aPromise
instance.It is the
Promise
instance on which you call thethen()
method, passing in a callback function, which will be eventually be fired when the async code finishes (and internally, callsresolve()
).As an example, here's what a custom
load
function might look like:Note that the
Promise
object will resolve any nested promises as part of its work, so resolvingres.json()
which results in aPromise
being created will be resolved internally before the final chained.then(console.log)
is called.The trick to Promises is:
Promise
s you create (or functions that returnPromise
s) so they can be chainedresolve()
orreject()
within the promiseexecutor
so.then()
or.catch()
will be called and the chaining will completeCreated an account just to say thank you for this breakdown.
Well that's very kind of you. I'm glad it helped!