Reputation: 685
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?
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
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