Understand “Promise” (2/3): Promise Instance

Step 1: In previous post, the result of axios.get(“/api/items”) is a Promise instance.



Step 2: But the original way to create a Promise instance is using Promise constructor.

1
2
3
4
5
6
7
8
9
10
11
12
// Promise constructor uses a callback as param.
// The callback uses other two callbacks as params.
// This is probably the hardest part for beginners.
const myPromise = new Promise((resolve, reject)=>{
    // Pseudo code below.
    I fetch some data from server;
    if (I fetched the data successfully){
        resolve(data);
    } else {
        reject(some_fail_information);
    }
});


Step 3: We now can use “myPromise” to call .then() or .catch()

1
2
3
4
5
6
7
myPromise
    .then((data_from_db)=>{
        console.log(data_from_db);
    })
    .catch((fail_info)=>{
        console.log(fail_info);
    });


Step 4: Only if resolve() is executed in step 2, then() in step 3 will be executed. Only if reject() is executed in step 2, catch() in step 3 will be executed.



Previous: Understand “Promise” (1/3): Axios Next: Understan “Promise” (3/3): Create a Simple “Axios”

Leave a Reply

Your email address will not be published. Required fields are marked *