3 回答
TA贡献1827条经验 获得超7个赞
是的,jQuery承诺存在严重的固有问题。
returnsPromise().then(a).then(b)
a
b
function timeout(){ var d = $.Deferred(); setTimeout(function(){ d.resolve(); },1000); return d.promise();}timeout().then(function(){ document.body.innerHTML = "First"; return timeout();}).then(function(){ document.body.innerHTML += "<br />Second"; return timeout();}).then(function(){ document.body.innerHTML += "<br />Third"; return timeout();});
然而,这两个 巨量jQuery的问题是错误处理和意外执行顺序。
错误处理
try/catch
.
timeout().then(function(){ throw new Error("Boo");}).then(function(){ console.log("Hello World");},function(){ console.log("In Error Handler"); }).then(function(){ console.log("This should have run");}).fail(function(){ console.log("But this does instead"); });
"uncaught Error: boo"
timeout().then(function(){ var d = $.Deferred(); d.reject(); return d;}).then(function(){ console.log("Hello World");},function(){ console.log("In Error Handler"); }).then(function(){ console.log("This should have run");}).fail(function(){ console.log("But this does instead"); });
"In Error Handler" "But this does instead"
try{ throw new Error("Hello World");} catch(e){ console.log("In Error handler");}console.log("This should have run");
执行命令
function timeout(){ var d = $.Deferred(); setTimeout(function(){ d.resolve(); },1000); return d.promise();}console.log("This");var p = timeout();p.then(function(){ console.log("expected from an async api.");});console.log("is");setTimeout(function(){ console.log("He"); p.then(function(){ console.log("̟̺̜̙͉Z̤̲̙̙͎̥̝A͎̣͔̙͘L̥̻̗̳̻̳̳͢G͉̖̯͓̞̩̦O̹̹̺!̙͈͎̞̬ *"); }); console.log("Comes");},2000);
setTimeout
旁注
.done
TA贡献2065条经验 获得超14个赞
"these filter functions can return a new value to be passed along to the promise's .done() or .fail() callbacks, or they can return another observable object (Deferred, Promise, etc) which will pass its resolved / rejected status and values to the promise's callbacks"
- 3 回答
- 0 关注
- 382 浏览
相关问题推荐
添加回答
举报