Promise 常用來處理非同步流程,當執行成功時 resolve( ) 處理 .done( ); 失敗時 reject( ) 處理 .fail( );另外當成功執行 .done 之後還可以透過 .then( ) 繼續執行其它的處理,避免過多 CallBack 處理程序而造成 CallBack hell 。範例內容如下,並可參考連結有更詳細的說明
HTML:
<button id="rs">ReSolve</button>
<button id="rj">Reject</button>
JQuery:
var def= jQuery.Deferred( );
$("#rs").click(() => def.resolve( )); // handle resolve
$("#rj").click(() => def.reject( )); // handle reject
var task = def.promise( );
task.done(
( ) => {alert('Resolve Clicked!');}) // success to handle .done
.then(
( ) => {alert('Call again for Resolve!');}) // next when .done finish
.fail(
( ) => {alert('Reject Clicked!');}) // fail to handle .fail
.always(
( ) => {$("button").prop("disabled", true);}); // here is always to handle without success or fail
參考連結: http://blog.darkthread.net/post-2016-12-22-js-promise.aspx
HTML:
<button id="rs">ReSolve</button>
<button id="rj">Reject</button>
JQuery:
var def= jQuery.Deferred( );
$("#rs").click(() => def.resolve( )); // handle resolve
$("#rj").click(() => def.reject( )); // handle reject
var task = def.promise( );
task.done(
( ) => {alert('Resolve Clicked!');}) // success to handle .done
.then(
( ) => {alert('Call again for Resolve!');}) // next when .done finish
.fail(
( ) => {alert('Reject Clicked!');}) // fail to handle .fail
.always(
( ) => {$("button").prop("disabled", true);}); // here is always to handle without success or fail
參考連結: http://blog.darkthread.net/post-2016-12-22-js-promise.aspx
留言
張貼留言