做爲一個容器,用於存儲將來要發生的事情,其狀態分別爲pending
,resolved
,rejected
。 javascript
缺點:基本在於若是他執行了,那麼沒法中途取消,若是沒有設置回調,則沒有返回結果,也沒有錯誤說明。
理解:
1. 一個異步須要很長時間執行時,對於promise
函數執行的方法是沒有辦法終止的。
2. 須要設置回調,沒法獲得返回或錯誤。(沒有回調寫個毛線啊!!)java
var promise = new Promise( function(resolve,reject){ if(/*執行成功*/){ resolve(value); }else{ reject(value); } } );
說明:
1. 在異步執行完成後,經過resolve(value)
或者reject(value)
能夠將在異步中獲取到值value
傳遞出去。交給promise.then()方法進行調用。
2. 同時then()
方法中return new_value
處理後的值實現值的再傳遞。shell
那麼,在then 方法中又出現異步的時候,是怎麼樣的狀況呢?針對的是內外都是
promise
函數promise
var p1 = new Promise((resolve,reject)=>{ setTimeout()=>{ reject(new Error('fail')),3000) } }); var p2 = new Promise(function (resolve, reject) { setTimeout(() => resolve(p1), 1000) }) p2.then(result => console.log(result)) .catch(error => console.log(error)) // Error: fail
說明:
1. p2執行調用了p1,這個時候,p1的狀態交給了p2。
2. 只有在p1的執行完成後,也就是被resolve或者reject以後,纔會執行p2的回調。異步
說明:async
- then():then()完整的方式是2個參數,分別爲resolve的後來執行,以及reject的後面執行。
- all():參數是一組promise,當都完成後,纔會執行回調。
- catch():將then()函數的方法單獨出來做爲一個請求。用於全局的異常錯誤處理。經過reject(err)的做用等同於拋出
錯誤
。- race():競爭上崗。
Promise.resolve()
: 等同new Promise(resolve=>resolve(foo))
,thenable
也就是一個返回有一個then
屬性的對象- 若是resolve()函數的方法沒有參數,也就是在異步以後執行。也就是在本次執行完成時候。
setTimeout(function () { console.log('three'); }, 0); Promise.resolve().then(function () { console.log('two'); }); console.log('one'); // one // two // three
- done():用於處理異常,捕捉錯誤,向着全局拋出。就是是done以後的異常是會被執行器捕獲到。
- finally():最後都會執行的方法。
我的的看法:
相似一個stack,因爲存放各種的處理的語言,能夠是異步,也多是同步,在執行next()的方法的時候,跳轉到下一個語句。函數
function* helloWorldGenerator() { yield 'hello'; yield 'world'; return 'ending'; } var hw = helloWorldGenerator(); //執行 hw.next() // { value: 'hello', done: false } hw.next() // { value: 'world', done: false } hw.next() // { value: 'ending', done: true } hw.next() // { value: undefined, done: true }
說明:如何使用generator()函數
1. thunk思想
2. co小工具工具
var gen = function* () { var f1 = yield readFile('/etc/fstab'); var f2 = yield readFile('/etc/shells'); console.log(f1.toString()); console.log(f2.toString()); }; var co = require('co'); co(gen); co(gen).then(function (){ console.log('Generator 函數執行完成'); });
注意:yeild
後面接的是promise()的對象。ui
是對generator函數的升級改造
javascript
code
var asyncReadFile = async function () {
var f1 = await readFile('/etc/fstab');
var f2 = await readFile('/etc/shells');
console.log(f1.toString());
console.log(f2.toString());
};
`` 包裹的字符串,同時${}來包裹變量