.then( ) and Async / wait explanation in JS

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值