Encapsulation of axios in vue

this is the code in my fresh

export function fetch(options) {
    return new Promise((resolve, reject) => {
        const instance = axios.create({
            //
            headers: {
                "Content-Type": "application/json",
            },
            timeout: 30 * 1000 // 30
        });
        instance(options)
            .then(response => {
                Message({
                    message: "",
                    type: "success"
                });
                resolve(response);
            })
            .catch(error => {
                reject(error);
            });
    });
}

this is the code in my index

export function test(params) {
    return fetch({
        url: api.test,
        method: "get",
        params
    })
}

now when I use it on a page, I can only get the return value in test through the .then () method. Is there any way to pass

on the page?
const res=test();

test().then(res=>{
    if(res){
    ....
    }
})

Dec.02,2021

async submit() {
   var result= await api.test()
}

first of all, Lou understands that your fetch returns a promise object, so your test method also returns a promise object. It is not the data returned by the interface. So there are two ways to deal with promise, one is . Then () , the other is async.await . The latter way of writing is more in line with the developer's Synchronize thinking .

Menu