1. Introduction
Synchronized and Async processing are confusing and hard to understand for beginner JavaScript learners. Today, I will use a simple scenario to explain the concept and usage of the asynchronous processing in JavaScript, have fun learning!
Let's assume that we want to make a banana milkshake. Here are the steps and ingredients of a tasty homemade milkshake:
Ingredients:
I.one beautiful banana,
II.250ml fresh milk
Steps:
1.peel the banana (1s)
2.cut the peeled banana into 6 pieces(3s)
3.put 250ml milk and banana pieces into a blender(2s)
4.start the blender and enjoy the milk(2s)
*Parentheses at the end of each step are the time needed in every step. Let's figure out how to illustrate the whole process in JavaScript code.
2. Simple Example and Callback hell
John is a new programmer who doesn't know how to handle the async situation properly, so he tries to solve it most simply. That is, enter each step one by one like this:
let production = () =>{
setTimeout(()=>{
console.log("peel the banana")
setTimeout(()=>{
console.log("cut the banana into 6 pieces")
setTimeout(()=>{
console.log("put 250ml milk and banana pieces into a blender")
setTimeout(()=>{
console.log("start the blender and enjoy it!")
},2000)
},2000)
},3000)
},1000)
}
Theoretically, he can achieve the result we want. However, this code is very hard for him and others to comprehend. The structure of this kind of code is called "Callback ."."ll". So, let's look at how to use then() and await to deal with it.
3. New Methods Include then(), and async/await
Here we must first understand a special object called "Promise" in JavaScript. According to the JavaScript web document: "The Promise object represents the eventual completion (or failure) of an asynchronous operation and its resulting value." -JavaScript Web Document
ke program, we first need to create a prom to deal with our banana milkshake programise object. Then we can use the then() method to finish the program step by step.
let we_have_banana = true;
let produce = (time, step) => {
return new Promise((resolve, reject)=>{
if(we_have_banana){
setTimeout(()=>{
console.log(step)
},time)
resolve(step)
}else{
reject(console.log('Sorry, we do not have any bananas'))
}
})
}
F all, the "we_have_banana" is a boolean to determwhether in the result returns resolve or rejects (error).
produce(1000,"peel the banana").then(() =>{
produce(3000,"cut the banana into pieces")}
).then(()=>{
produce(2000,"put milk and banana into a blender")
}).then(()=>{
produce(2000,"start the blender and enjoy it!")
})
As we can see, when we use the then() method, the code is much clearer and easier to understand.
Finally, let's see how to use the async/await method to do the same work. The async/await method is even simpler for us to understand, as the logic is pretty straightforward. Here is the code example:
let we_have_banana = true;
function processtime(ms){
return new Promise((resolve,reject)=>{
if(we_have_banana){
setTimeout(resolve,ms)
}else{
reject(console.log("we have no banana anymore"))
}
}
)}
async function process(){
try{
await processtime(1000)
console.log('peel the banana')
await processtime(3000)
console.log('cut the banana into 6 pieces')
await processtime(2000)
console.log('put milk and banana into a blender')
await processtime(2000)
console.log('start the blender and enjoy it!')
}catch(error){
console.log('no banana milkshake to enjoy')
}
}
4. Conclusion
Understanding the logic and details of the asynchronous procession in JavaScript is crucial in front-end programming. The asynchornous JavaScript concept is widely used in the latest frameworks like Vue and React. Meanwhile, many useful tools like ajax also need the knowledge of asynchronous procession.
本文通过制作香蕉奶昔的场景,深入浅出地讲解JavaScript异步处理,包括回调函数的困扰、Promise及then()方法的应用,最后对比async/await的简洁易懂。了解异步对前端开发至关重要,尤其在Vue和React等现代框架中
1279

被折叠的 条评论
为什么被折叠?



