1. Call back the appearance of hell
Here’s an example:
In the morning, I went to eat breakfast, breakfast store in accordance with the habit called soya-bean milk and Fried dough sticks, for soybean milk is already prepared, and is now the Fried dough sticks, I could not immediately to eat, assuming that soya-bean milk get after 1 s, 2 s after got Fried dough sticks, but I used to eat eat a mouthful of Fried dough sticks, then drink a mouthful of soya-bean milk, then there are the following:
function SoyaBeanMilk(fn){
setTimeout(() = >{
fn('soya-bean milk)},1000)}function friedBreadStick(fn){
setTimeout(() = >{
fn('Fried dough sticks')},2000)
}
friedBreadStick(function(data){
console.log(data);
SoyaBeanMilk(function(data){
console.log(data); })})Copy the code
Output results: the first 2s to get fried dough sticks, then 1s to get soybean milk
2. Call back the hell phenomenon
When eating fried dough sticks, drinking soybean milk, I still did not eat full, in eating something else, gradually produced a callback hell phenomenon
After asking the boss for two steamed buns and a few shaomai, the result is as follows:
friedBreadStick(function(data){
console.log(data);
SoyaBeanMilk(function(data){
console.log(data);
XXX(function(data){
console.log(data);
XXX(function(data){
console.log(data);
XXX(function(data){
console.log(data); })})})})})Copy the code
It’s a horrible piece of code, it’s like poop, it’s not easy to maintain,
Thus, ES6 leads to the promise object
3. Promise
For details on how to use promises, see the ===> promise object in js
The promise transmits asynchronous data through the resolve parameter, which is retrieved through then
Next modify the above code
function SoyaBeanMilk(){
return new Promise(function(resolve){
setTimeout(() = >{
resolve('soya-bean milk)},1000)})}function friedBreadStick(){
return new Promise(function(resolve){
setTimeout(() = >{
resolve('Fried dough sticks')},2000)
})
}
friedBreadStick().then(function(data){
console.log(data);
return SoyaBeanMilk()
}).then(function(data){
console.log(data);
})
Copy the code
The result was still the same:
I used the chained version of Promise, which made the code a little cleaner, but still a little harder to maintain
So, async, await again
4. async await
‘await’ is followed by a promise object to get the value returned by ‘resolve’ and can be assigned
Await will wait for the asynchronous program to finish before executing the following code, so it looks like synchronous code
async function getBreakfast(){
let friedBreadStick = await friedBreadStick();
console.log(friedBreadStick);
let SoyaBeanMilk = await SoyaBeanMilk();
console.log(SoyaBeanMilk);
}
Copy the code
Pros :(more like synchronous code) clean structure, easy maintenance, and no callback hell