我有这个测试用例:
function setInitialValues (data) {
window.localStorage.setItem ("name", "some name");
}
var data = '';
$.when (setInitialValues (data)).then (function (data) {
window.localStorage.getItem ("name"); // this will be 'undefined' instead of 'some name'
});
在我致电name
set
未获得getItem
会发生什么?
任何想法如何解决这个问题?
答案 0 :(得分:0)
您需要从方法
返回一个承诺function setInitialValues (data) {
var deferred = jQuery.Deferred();
//if some async operation is going on here then to simulate
setTimeout(function(){
window.localStorage.setItem ("name", "some name");
deferred.resolve()
}, 10)
return deferred.promise();
}
演示:Fiddle