我有一个代码,用于在内存存储中搜索某些数据,如果没有找到,则在服务器上搜索该数据并将其缓存在内存中。 如何将对象作为Promise返回,以便调用者可以在其上调用“done”?
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
......
);
}
答案 0 :(得分:3)
您需要返回承诺
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
......
);
}