“This is the 23rd day of my participation in the First Challenge 2022. For details: First Challenge 2022.”
What is callback hell
When a function is called as an argument in a method, the function is called a callback function. If you pass another function inside the callback function, you can create callback hell
Callback hell is a bad coding habit, unreadable and difficult to maintain, as shown in the following code
const process = (msg, cb) = > {
setTimeout(() = > {
console.log(msg)
cb()
}, 1000)
}
process('msg 1'.() = > {
process('msg 2'.() = > {
process('msg 3'.() = > {
process('msg 4'.() = > {
console.log('end')})})})})Copy the code
How to solve callback hell
The way to solve callback hell is to take the layers of nested callback functions and flatten them out
Thunk function
Thunk function Thunk function Thunk function
The Thunk function is an “old” concept, dating back to the 1960s. In Javascript, it’s a combination of currizing, converting a multiparameter version of a function to a single-parameter version and returning a new function that accepts only callback functions as arguments.
- Modify the above example to use the Thunk function plus an execution function to save callback hell by maintaining an array of execution orders
const process = (msg, cb) = > {
setTimeout(() = > {
console.log(msg)
cb && cb()
}, 1000)}/ / thunk function
const thunk = (msg) = > (cb) = > process(msg, cb)
const p1 = thunk('msg 1')
const p2 = thunk('msg 2')
const p3 = thunk('msg 3')
const p4 = thunk('msg 4')
// Order of execution
const arr = [p1, p2, p3, p4]
// Execute the function
const gen = (arr) = > () = > arr.reduceRight((a, b) = > () = > b(() = > a()))()
const run = gen(arr)
run()
Copy the code
Promise
Chain operation is adopted and calls are made in sequence. In THEN, the state of the previous Promise will be Fulfilled after becoming a pity, and a Promise object will be returned
- Let’s use the previous example
Promise
Wrapping up a layer, you can see how elegant it is to switch to chain calls
const process = (msg, cb) = > {
setTimeout(() = > {
console.log(msg)
cb && cb()
}, 1000)}const processPromise = msg= > {
return new Promise((resolve, reject) = > {
process(msg, resolve)
})
}
processPromise('msg 1')
.then(_= > processPromise('msg 2'))
.then(_= > processPromise('msg 3'))
.then(_= > processPromise('msg 4'))
Copy the code
async/await
Async /await is a syntactic candy of Promise, which will return a Promise object resolve value by default. Then operations can be performed directly, and chain operations can be changed to sequential execution (asynchronous waiting).
const run = async() = > {await processPromise('msg 1')
await processPromise('msg 2')
await processPromise('msg 3')
await processPromise('msg 4')
}
run()
Copy the code