I learned about async and promise a long time ago, but always smattering.
Today, when writing Nodejs, found a lot of third-party libraries using callbacks, so in the actual operation will appear multiple callbacks, this is the legendary JS callback hell.
As an example,
There is a way to call Redis, access a hash object table, get the return value, and insert the return value into the other hash object table of Redis.
Testcallbackaction () {Let Redis = redisclient (); Let key = ' xx '; Redis.hget (Redistable1,key, (err,data) =>{err& &think.logger.error (err); Redis.hset (Redistable2,key,data, (err,data) =>{console.log (err); Console.log (data );});})}
In the above method, it is possible to see that it is nested with 2 callback functions. With the complexity of the business, it inevitably leads to the infinite nesting of callback functions.
Async and promise can be used to solve this problem.
The first thing to know is a promise and async concept.
Promise can be seen as an asynchronous container. It can put an asynchronous calling method into a container, and in asynchronous processing, it does not jump directly to the next step, but instead blocks until the asynchronous processing ends and returns a resolve () method.
And ANSYC, await is promise natural pair of partner.
When executing promise, use ANSYC to designate promise as an async method, and then use await to wait for promise to return to the Resolve method.
In this way, we can simplify the above code, specifically as follows:
Async Testcallbackaction () {Let Redis = redisclient (); Let key = ' xx '; let RT = Null;await New Promise ((resolve, reject) = {Redis.hget (Redistable1,key, (err,data) =>{err&&think.logger.error (ERR); RT = Data;resolve ();})}) Await new Promise ((Resolve, Reject) =>{redis.hset (Redistable2,key,rt, (ERR) =>{console.log (ERR); resolve ();});})}
With this method, you can take the callback function apart, wait for the callback to end, and then perform the next step without nesting the callback, which greatly improves the readability of the code.
"JavaScript" uses async and Promise to perfectly resolve callbacks to hell