How to wrap object in a Promise?

2019-07-11 13:46发布

问题:

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

            );
    }

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

    );
}