[front end interview questions] use of Promise (solve asynchronous programming and callback)

catalogue

What is Promise?

What are the advantages of Promise?

What is asynchronous programming?

What is hell?

How to solve the problem? (Promise)

How to implement asynchronous programming - Comparison between the old and the new (New: Promise; old: callback function)

fs file operation

AJAX network request

timer

Database read

What is Promise?

Promise is a new technology introduced by ES6 and a new scheme to realize asynchronous programming. Promise is a constructor that encapsulates an asynchronous operation and can obtain the result value of its success or failure.

What are the advantages of Promise?

Promise can realize asynchronous programming, support chain call, and solve the callback problem.

What is asynchronous programming?

Asynchronous programming allows us to execute a long-time task without waiting. Instead, the program continues to execute the subsequent code until the execution is completed, and then comes back to inform you, usually in the form of callback function. This mode avoids the blocking of the program and greatly improves the execution efficiency of the CPU.

What is hell?

Callback functions are nested calls. The result of asynchronous execution of external callback functions is the condition for the execution of nested callbacks.

Disadvantages: 1. It is not easy to read; 2. Not convenient for exception handling

setTimeout(() => {
    console.log('Wait three seconds');
    setTimeout(() => {
        console.log("Wait another three seconds");
        setTimeout(() => {
            console.log("Wait another three seconds");
        }, 3000);
    }, 3000);
}, 3000);
//Execution result: three seconds later - > output "wait three seconds"; Wait another three seconds - > output "wait another three seconds"; Wait another three seconds - > output "wait another three seconds"
//It takes a total of 9 seconds to complete

This situation is called "callback hell".

How to solve the problem? (Promise)

//The chained call definition method is used to return the promise object
function promiseTime(str) {
    return new Promise((resolve, reject) => {
        //Business code
        setTimeout(() => {
            resolve(str);
        }, 3000);
    })
}

//implement
promiseTime('Wait three seconds')
    .then((value) => {
        console.log(value)
        return promiseTime('Wait another three seconds')
    })
    .then((value) => {
        console.log(value)
        return promiseTime('Wait another three seconds')
    })
    .then((value) => {
        console.log(value)
    })
//Execution result: three seconds later - > output "wait three seconds"; Wait another three seconds - > output "wait another three seconds"; Wait another three seconds - > output "wait another three seconds"
//It takes a total of 9 seconds to complete

The above is the method of Promise chain call to solve the callback problem.

How to implement asynchronous programming - Comparison between the old and the new (New: Promise; old: callback function)

1. fs file operation

You need to add a 'file Txt '.

//Read the contents of txt file
const fs = require('fs');

//Form of callback function
fs.readFile('./file.txt', (err, data) => {
    //If it fails, a failure error will be reported
    if (err) throw (err);
    //Output the contents of txt
    console.log(data.toString())
})

//promise form
let p = new Promise((resolve, reject) => {
    fs.readFile('./file.txt', (err, data) => {
        //If it fails, a failure error will be reported
        if (err) reject(err);
        //Output the contents of txt
        resolve(data.toString())
    })
})
//Call then
p.then((data) => {
    console.log(data)
}, (reason) => {
    console.log(reason)
})

2. AJAX network request

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Promise-AJAX</title>
</head>

<body>
    <button>Request interface (callback function)</button>
    <button>Request interface( Promise)</button>
    <script>
        //Get btn callback function DOM
        const btn = document.getElementsByTagName('button');
        btn[0].onclick = function () {
            //Form of callback function
            const xhr = new XMLHttpRequest();
            xhr.open('GET', 'https://api.apiopen.top/getJoke');
            xhr.send();
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4) {
                    //Judgment response status code 2xx
                    if (xhr.status >= 200 && xhr.status < 300) {
                        //Console output response body
                        console.log(xhr.response)
                    } else {
                        //Console output response status code
                        console.log(xhr.status)
                    }
                }
            }
        }
        //Get BTN promise DOM
        btn[1].onclick = function () {
            //Promise form
            const p = new Promise((resolve, reject) => {
                const xhr = new XMLHttpRequest();
                xhr.open('GET', 'https://api.apiopen.top/getJoke');
                xhr.send();
                xhr.onreadystatechange = function () {
                    if (xhr.readyState === 4) {
                        //Judgment response status code 2xx
                        if (xhr.status >= 200 && xhr.status < 300) {
                            //Console output response body
                            resolve(xhr.response)
                        } else {
                            //Console output response status code
                            reject(xhr.status)
                        }
                    }
                }
            })
            p.then((data) => {
                console.log(data)
            }, (reason) => {
                console.log(reason)
            })
        }
    </script>
</body>

</html>

3. Timer (see "callback hell")

4. Database read (async and await are used here)

Async is used to mark functions as asynchronous functions (referring to functions whose return value is Promise object). Other asynchronous functions can be used, but then is no longer needed. Instead, wait for Promise to be completed through await, and then execute the subsequent code in async, but will not block the execution of other code outside async.

The above is the use of Promise, including asynchronous programming, callback hell, chain call, async and await.

I'm front-end Dai, a coder who will share my common problems in projects and knowledge of written interviews with you at CSDN. I hope you can make progress together and come on.

Keywords: Javascript Front-end React

Added by sac0o01 on Tue, 21 Dec 2021 02:15:55 +0200