Skip to content Skip to sidebar Skip to footer

How To Wrap Object In A Promise?

I have a code that searches for some data in memory storage and if not found searches that data on server and caches it in memory. How can I return an object as a Promise so that t

Solution 1:

You need to return a promise

if (foundInLocalStorage) {
    var defered = $.Deferred();
    defered.resolve(dataFound);//resolve the promise with the data found
    //or setTimeout(defered.resolve.bind(promise, 5)); if you want to maintain the async nature
    return defered.promise();//return a promise

} else {
    return $.ajax({
        url: someUrl,
        dataType: 'json',
        data: {
            id: 101
        }
    }).done(
    //That part is fine
    ......

    );
}

Post a Comment for "How To Wrap Object In A Promise?"