Callback function and callback function

Posted by luvburn on Thu, 03 Mar 2022 14:31:07 +0100

catalogue

1, Promise object

1. Callback function

2. Synchronization task

3. Asynchronous task

4. Callback Hell: the case of nesting callback functions in callback functions is called callback hell (an operation method to realize the sequential execution of code)

5. Solution to callback hell

6. About Promise objects

2, async and await functions

1. async is used to decorate a function: it means that the function is asynchronous

2. await is used to decorate functions

3. Basic rules for using async/await

4. Difference between promise and async/await

1, Promise object

1. Callback function

When a function is passed into another function as a parameter, and the function will not be executed immediately; The function is executed only when a condition is met

function fn(){
		console.log('Mountain and sea')
	}
setTimeout(fn,3000) //fn is the callback function

2. Synchronization task

In the main thread queue, the next task will be executed only after the previous task is completed

3. Asynchronous task

Instead of entering the main thread queue, it enters the asynchronous queue. Whether the previous task is completed or not does not affect the execution of the next task (the tasks executed by subsequent tasks are not blocked)

setTimeout(function (){
    console.log('Callback function executed')
},3000)
console.log(111)

//    111
//    Callback function executed

If the code is written in the order, you should first output "callback function executed" and then output "111". But the actual output is not. Such tasks that do not block the execution of subsequent tasks are called asynchronous tasks.

4. Callback Hell: the case of nesting callback functions in callback functions is called callback hell (an operation method to realize the sequential execution of code)

setTimeout(function(){
    console.log('Day after day, month after month');
    setTimeout(function(){
        console.log('Month after month and year after year');
        setTimeout(function(){
            console.log('Return to this life year after year')
        },1000)
    },2000)
},3000)

//    Day after day, month after month
//    Month after month and year after year
//    Return to this life year after year

Callbacks in this nested function are called callbacks in hell. Callback hell is an operation that occurs to realize the sequential execution of code

(1) The readability and maintainability of the code are poor

(2) Poor code scalability

5. Solution to callback hell

(1) promise object

(2) async and await functions

6. About Promise objects

(1) It is a native JavaScript object and a solution for asynchronous programming. It avoids more callbacks through one callback

(2) Three states: pending (initial state), restored (operation succeeded) and rejected (operation failed)

(3) In short, Promise is a container that holds the results of an event (usually an asynchronous operation) that will not end in the future. Syntactically speaking, Promise is an object from which you can get the message of asynchronous operation

(4) Promise details

If the Promise state changes, it will be triggered The response function in then() handles subsequent steps

Once Promise state is changed, it will not change again

Once the Promise instance is created, the actuator executes it immediately

(5) Usage:

① The constructor has two parameters: reloved and rejected, both of which are callback functions

resloved function: call after successful asynchronous operation, and pass the result of asynchronous operation.

3. rejected function: after asynchronous operation fails, it sends the failed information out.

④ . then(): receive the information passed by the reloved function

⑤ catch(): receive the information passed by the rejected function

function fn(str){  //str = 'day after day, month after month'
    //Create Promise object
    let p = new Promise(function(resolve,reject){
        let flag = true;
        setTimeout(function(){  //Simulate asynchronous call
            if(flag){  //Simulated asynchronous call succeeded
                resolve(str)  //Pass str through resolve - resolve('day after day, month after month ')
            }else{  //Failed to simulate asynchronous call
                reject("operation failed")  //Pass the failed information through reject
            }
        })
    })
    return p;
}

fn('Day after day, month after month').then((data)=>{  //. then receives the message from resolve(str)
    console.log(data);  //data = ('day after day, month after month')
    return fn('Month after month and year after year');
}).then((data)=>{
    console.log(data);  //data = ('month after month and year after year')
    return fn('Return to this life year after year')
}).then((data)=>{
    console.log(data)  //data = ('return to this life every year')
}).catch((err)=>{
    console.log(err)
})

//    Day after day, month after month
//    Month after month and year after year
//    Return to this life year after year

2, async and await functions

1. async is used to decorate a function: it means that the function is asynchronous

2. await is used to decorate functions

It means to wait for the operation result of the modified function to come out before performing subsequent operations. It must be used in async modified functions and cannot be used alone

var sleep = function(time){
    return new Promise((resolve,reject)=>{
        setTimeout(()=>{
            resolve('Blooming and withering')
        },time);
    })
}
var start = async function(){
    console.log('Rain comes and geese go, oblique fog drizzle')
    await sleep(3000).then(data=>{
        console.log(data)  //data = 'blooming and withering'
    })
    console.log('How many degrees of time do you encounter in one phase')
}

start()

//    Rain comes and geese go, oblique fog drizzle
//    Blooming and withering
//    How many degrees of time do you encounter in one phase

3. Basic rules for using async/await

(1) The await keyword can only be used in functions defined using async

(2) await can be directly followed by a Promise instance object (any expression can be followed, and more importantly, an expression that returns the Promise object)

(3) The await function cannot be used alone

(4) await can directly get the data in Promise and resolve

function fn(str){  //str = 'day after day, month after month'
    //Create Promise object
    let p = new Promise(function(resolve,reject){
        let flag = true;
        setTimeout(function(){  //Simulate asynchronous call
            if(flag){  //Simulated asynchronous call succeeded
                resolve(str)  //Pass str through resolve - resolve('day after day, month after month ')
            }else{  //Failed to simulate asynchronous call
                reject("operation failed")  //Pass the failed information through reject
            }
        })
    })
    return p;
}

async function test(){
    let s1 = await fn('Rain comes and geese go, oblique fog drizzle')
    let s2 = await fn('Blooming and withering')
    let s3 = await fn('How many degrees of time do you encounter in one phase')

    console.log(s1,s2,s3)
}
test()

//    Rain comes, geese go, oblique fog, drizzle is in full bloom and withers, and how many times do you encounter once in a period

Note: (1) the information passed by resolve of Promise object can be obtained directly without using then

(2) Use try Catch to capture the asynchronous operation failure information passed by the reject of Promise object

4. Difference between promise and async/await

(1) promise is ES6 and async/await is ES7

(2) async/await is more elegant than promise

(3) reject status

① promise errors can be caught through catch. It is recommended to catch errors at the tail

② async/await can be used either then can be captured with try catch

Topics: Javascript Front-end