user3284063
user3284063

Reputation: 685

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 the caller can just invoke a "done" on it?

The code looks like that:

if (foundInLocalStorage)
    {
    // This part I cannot make to work, caller does not have its 'done' fired
        var defered = $.Deferred();
        defered.resolve();
        defered.promise(dataFound);
    }
    else
    {
        return $.ajax
            (
            {
                url: someUrl,
                dataType: 'json',
                data: { id: 101 }
            }
            )

            .done
            (
//That part is fine
              ......

            );
    }

Upvotes: 3

Views: 2795

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388316

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
    ......

    );
}

Upvotes: 3

Related Questions