如何在Promise中包装对象?
我有一个代码在内存存储中搜索一些数据,如果没有找到,则在服务器上搜索该数据并将其缓存在内存中。 如何将对象作为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 ...... ); }
你需要回复一个承诺
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 ...... ); }