Understand “Promise” (3/3): Create a Simple “Axios”

In previous post, I used some Pseudo code in Promise constructor, now I will create a Promise instance with real code, and for better understanding, I will use JQuery to do ajax call.

Step 1: the origin is axios.get(url), it looks like some instance call its function, so I will start with creating our own axios class, let’s name it MyAxios.



Step 2: Create a static method get() in MyAxios, so that we can call it without instantiate any objects. And our get() shall take an url as param:

1
2
3
4
5
class MyAxios{
    static get(url){
        pass;
    }
}


Step 3: Remeber axios.get(url) returns us a Promise instance, so we need the same:

1
2
3
4
5
6
7
class MyAxios{
    static get(url){
        return new Promise((resolve, reject)=>{
            pass;
        });
    }
}


Step 4: JQuery ajax method already provides success and fail call back, so in order to utilize resolve and reject, we can write all our ajax call inside Promise:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class MyAxios{
    static get(url){
        return new Promise((resolve, reject)=>{
            $.ajax({
                type: 'GET',
                url: url,
                success: function(data) {
                    resolve(data);
                },
                error: function(err) {
                    reject(err);
                };
            });
        });
    }
}


Step 5: Now we are able to use MyAxios.get() like axios.get(), only my version is trimmed and simplified.



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

Leave a Reply

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