Home  >  Article  >  Web Front-end  >  Let you understand Promise through code examples

Let you understand Promise through code examples

青灯夜游
青灯夜游forward
2023-03-01 20:08:261779browse

This article uses multiple code examples to help you understand the basic usage of Promise, and further master the idea of ​​Promise asynchronous access.

Let you understand Promise through code examples

I have always heard of the reputation of Promise before, but I always felt that it was a more profound thing, and I was a little afraid of it and failed to really understand it. I recently watched the Node.js video uploaded by Mr. Li Lichao at Station B. I felt that the explanation was very clear, so I will further sort it out here.

Let’s look at a problem first

We all know that JavaScript runs in a single thread, so if you encounter a situation where data takes a while to be obtained, just It will cause blocking and the subsequent code cannot be executed, which is quite fatal. For example, the while statement in the middle of the following code

function sum(a, b) {
    const begin = Date.now();
    while(Date.now() - begin < 10000) {

    }
    return a+b;
}

console.log(sum(1,2));
console.log("1");

went through a 10-second loop, and finally printed out 3 and 1

# respectively. ##However, what we want is to allow 3 to be printed out after 10 seconds, but 1 must be printed out first

Here we use

setTimeout, and modify the code as follows

function sum(a, b) {
    setTimeout(() => {
        return a+b;
    },10000)
}

console.log(sum(1,2));
console.log("1");

Run it and you will see that 1 is indeed printed instantly, but the position where 3 should be printed is undefined

Let you understand Promise through code examples

The reason is that

console.log at this time There is no waiting eithersetTimeoutAfter finishing, the data after 10 seconds cannot be received

So in order to receive the data after 10 seconds, we can use the callback function

function sum(a, b, callback) {

    setTimeout(() =>{
        callback(a+b);
    }, 10000)

}

sum(1,2,(result) => {
    console.log(result);
});
console.log("1");

Passed in a callback function that can receive a b as parameters

(result) => {console.log(result);}

So after 10 seconds This callback function will be executed and printed. The result is as follows

Let you understand Promise through code examples

#In this way, we have initially solved this problem. A data that needs to be obtained with a delay will be executed first and then be retrieved. Obtain.

However, Promise has not yet appeared, which involves another area that needs improvement

Callback hell

This sounds very bluffing at first glance The name is actually a situation caused by the nesting of multiple layers of callback functions that is not conducive to reading and debugging.

For example, we want to call this sum function multiple times at this time. After getting the result of 1 2, we need to get the results of 1 2 3 and 1 2 3 4.

So we have to In the callback function passed in by sum, sum is called multiple times for nesting, as follows

sum(1,2,(result) => {
    sum(result, 3, (result) => {
        sum(result, 4, (result) => {
            console.log(result);
        })
    })
});

Let you understand Promise through code examples

This pyramid-like structure is poorly readable and difficult to debug, and is called Callback hell.

So it’s finally time for Promise to appear, and its appearance solves the problem of callback hell.

What is Promise

Before using Promise to solve the problem of callback hell, let’s first have a general understanding of what Promise is.

My current judgment is that Promise is an object used to access asynchronous data.

First let’s take a look at what an empty Promise will look like when printed out

const promise = new Promise(()=>{});

Let you understand Promise through code examples

The most critical of these are the two values ​​​​PromiseState and PromiseResult, which will be expanded in detail later. , here you just need to know that Promise has these two properties.

Let’s take a look at the process of storing data in promise. The most important thing is to know that there is resolve and reject. For example, the following code

const promise = new Promise((resolve, reject) => {
    const flag = true;
    if (flag) {
        resolve("resolve datas");
    } else {
        reject("reject data");
    }
})

At this time, the flag is true, so the storage of resolve is executed. , the result obtained is as follows

Let you understand Promise through code examples

And when we change the flag to false and execute the storage of reject, the result obtained is as follows

Let you understand Promise through code examples

Now it’s time to explain the above two properties.

    When promise does not store data, the value of PromiseState is pending and the value of PromiseResult is undefined
  • When promise When using resolve to store data, the value of PromiseState is pending, and the value of PromiseResult is the corresponding stored value
  • When promise uses reject to store data, the value of PromiseState is rejected, and the value of PromiseResult is the corresponding stored value
Since there are two types, reading is naturally divided into two types

When we read the data in the promise, we need to use the following structure

promise.then(result => {
    console.log(result);
}, reason => {
    console.log(reason);
})

If the data If it exists in resolve, result will return the result. If it exists in reject, reason will return the result.

Use Promise to solve callback hell

After a preliminary understanding of Promise, you will find that what Promise can currently do can also be done using callback functions.

So the most important thing is that Promise solves the callback hell. For example, the previous problem can be written in this form

function sum(a, b) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve(a+b);
        }, 1000);
    })
}

sum(1,2)
    .then(result => sum(result,3))
    .then(result => sum(result,4))
    .then(result => {
        console.log(result);
    })

promise 通过then方法进行读取后,是个新的Promise对象,比如我们可以打印一下

function sum(a, b) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve(a+b);
        }, 1000);
    })
}

console.log(sum(1,2)
    .then(result => sum(result,3)))

Let you understand Promise through code examples

所以这也就给了我们能多次调用then方法的基础。

而这也就解决了回调地狱的问题。

小结

Promise 是一个可以存取异步数据的对象,通过resolvereject来存储数据,可以通过then来读取数据

至于其他的.catch .finally .race .any .all 这些方法就不再多作赘述,详细的见文档

【推荐学习:javascript高级教程

The above is the detailed content of Let you understand Promise through code examples. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:juejin.cn. If there is any infringement, please contact admin@php.cn delete