Promises

How diff from callbacks?

Callbacks can’t give the returned value to the rest of the program. It only lets you play around with “side-effects” (just a state being changed)

Using pure callbacks results in the pyramid of doom. You have callbacks within callbacks.

readFile(“file”, (err, res)=>{
if (err) return err;
readFile(“file”, (err, res)=>{
if (err) return err;
// etc.
}
})

Or you could use try catch. etc. essentially, this way really sucks.

that’s where Promises come in.

——————————————

return itself is synchronous. doesn’t allow much flexibility. return will return immediately. We can’t save it into another variable.

You don’t want the next one to run before you finish reading file etc.

This was my point of confusion: the executor function needs to have two params: a resolve and reject parameter, each of which specify the

.then

and

.catch

Key point: promises are pending until they are resolved/rejected

console.log(myPromise) // pending
myPromise.then // this will week to resolve it
// once it does, it passes the value to the next then
// or if it's error, it passes to the next catch
Like what you read? Give Franklyn Zhu a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.