https://www.promisejs.org/jquery
What is a promise?
The core idea behind promises is that a promise represents the result of an asynchronous operation. A promise is in one of three different states:ajax
- pending - The initial state of a promise.
- fulfilled - The state of a promise representing a successful operation.
- rejected - The state of a promise representing a failed operation.
Once a promise is fulfilled or rejected, it is immutable (i.e. it can never change again).shell
promise的核心思想是, promise能夠表示異步操做的的結果。 包括三個狀態, pending, fulfiled, rejectedapi
promise 在英文中是諾言, fulfil promise 爲實現諾言, rejected promise 爲 收回諾言。 分別表示成功和失敗。promise
用promise 來描述異步操做結果, 是太形象了, 在當下定義了一個 promise, 諾言的結果, 須要在未來來驗證, 不影響當下的運行計劃,異步
例如, 你對你老婆說, 你未來必定要買個大房子給你老婆住。 在你說的時候, 不影響你當天或者明天的工做和生活計劃, 該編碼就編碼, 該散步就散步, async
至於之後能不能買到大房子, 那是之後的事情了, 固然諾言要有個期限, 期限已到, 按照諾言, 須要買房, 若是能買到則 fulfill promise, 若是未實現,則reject promise。ide
以下面例子: 函數
定義了一個讀取文件的 promise, 讀取成功了調用 fulfill回調, 讀取失敗了 調用 reject回調。編碼
function readFile(filename, enc){ return new Promise(function (fulfill, reject){ fs.readFile(filename, enc, function (err, res){ if (err) reject(err); else fulfill(res); }); }); }
若是沒有promise, 則例如上例中, 異步讀取動做, 咱們須要在咱們的回調函數callback中, 處理各類錯誤狀況, 和成功狀況。
錯誤狀況, 包括:
一、 讀取文件失敗
二、 解析讀取數據失敗
成功狀況:
一、 解析讀取數據成功
使用promise後, 對於成功的狀況, 定義成功的處理函數, 對於失敗的狀況, 定義失敗的處理函數。 代碼邏輯異常清晰。
function readJSON(filename, callback){ fs.readFile(filename, 'utf8', function (err, res){ if (err) return callback(err); try { res = JSON.parse(res); } catch (ex) { return callback(ex); } callback(null, res); }); }
除了第一節中, 構造一個promise的例子, 指出要指定 fulfill 和 reject 回調函數, 若是在異步操做完成後, 想作一些其餘動做, 則能夠調用以下接口,進行定義:
use
.then
whenever you're going to do something with the result (even if that's just waiting for it to finish)use
.done
whenever you aren't planning on doing anything with the result.
function readJSON(filename){ return readFile(filename, 'utf8').then(function (res){ return JSON.parse(res) }) }
結合 then 和 catch接口, 實現的例子:
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch
var p1 = new Promise(function(resolve, reject) { resolve("成功"); }); p1.then(function(value) { console.log(value); // "成功!" throw "哦,不!"; }).catch(function(e) { console.log(e); // "哦,不!" });
https://api.jquery.com/jQuery.ajax/#jqXHR
$.ajax({ url: "http://fiddle.jshell.net/favicon.png", beforeSend: function( xhr ) { xhr.overrideMimeType( "text/plain; charset=x-user-defined" ); } }) .done(function( data ) { if ( console && console.log ) { console.log( "Sample of data:", data.slice( 0, 100 ) ); } });
API
- jqXHR.done(function( data, textStatus, jqXHR ) {});
An alternative construct to the success callback option, refer to
deferred.done()
for implementation details.- jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});
An alternative construct to the error callback option, the
.fail()
method replaces the deprecated.error()
method. Refer todeferred.fail()
for implementation details.- jqXHR.always(function( data|jqXHR, textStatus, jqXHR|errorThrown ) { });
An alternative construct to the complete callback option, the
.always()
method replaces the deprecated.complete()
method.In response to a successful request, the function's arguments are the same as those of
.done()
: data, textStatus, and the jqXHR object. For failed requests the arguments are the same as those of.fail()
: the jqXHR object, textStatus, and errorThrown. Refer todeferred.always()
for implementation details.- jqXHR.then(function( data, textStatus, jqXHR ) {}, function( jqXHR, textStatus, errorThrown ) {});
Incorporates the functionality of the
.done()
and.fail()
methods, allowing (as of jQuery 1.8) the underlying Promise to be manipulated. Refer todeferred.then()
for implementation details.
https://www.promisejs.org/api/
每一個API都有簡單的使用介紹, 非常淺顯易懂, i like it。
var p1 = new Promise(function(resolve, reject) { resolve("Success"); }); p1.then(function(value) { console.log(value); // "Success!" throw "oh, no!"; }).catch(function(e) { console.log(e); // "oh, no!" }); setTimeout(function(){ p1.then(function(value) { console.log(value); // "Success!" throw "oh, no!"; }).then(undefined, function(e) { console.log(e); // "oh, no!" }); }, 2000)