简体   繁体   中英

Is there a way to trigger the done function on a jQuery AJAX call?

I have a function that should only continue after an AJAX call has been completed, but I want to be able to skip that AJAX call if I already have the data from last session in my localstorage.

My current code:

$.when(getAddresses()).done(function (data) {
        addresses = data.data;;

        localStorage['addresses'] = JSON.stringify(addresses);

        {{Rest of the code that should be executed after the AJAX call}}
}

Thanks in advance!

Do it the other way around.

Check for the data locally and don't even send the request if you already have it.

Wrap the data in a promise so it will always have the same API no matter where you fetch it from.

async function get_data() {
    let addresses = localStorage.getItem('addresses');
    if (addresses) {
         return JSON.parse(addresses);
    }
    let ajaxData = await getAddresses();
    addresses = ajaxData.data;
    localStorage.setItem('addresses', JSON.stringify(addresses));
    return addresses;
}

get_data().then(data => {
    // Rest of the code that should be executed after the AJAX call
});

Another approach would be to forget about localStorage and just have the web service set suitable caching headers . Then you can make the HTTP request, but if the cache information shows that the browser cache contains up to date data it won't make the HTTP request at all.

You don't need to reinvent local caching of data. HTTP has it baked in.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM