Javascript中的神器——Promise
Promise in js
回調(diào)函數(shù)真正的問(wèn)題在于他剝奪了我們使用 return 和 throw 這些關(guān)鍵字的能力。而 Promise 很好地解決了這一切。
2015 年 6 月,ECMAScript 6 的正式版 終于發(fā)布了。
ECMAScript 是 JavaScript 語(yǔ)言的國(guó)際標(biāo)準(zhǔn),JavaScript 是 ECMAScript 的實(shí)現(xiàn)。ES6 的目標(biāo),是使得 JavaScript 語(yǔ)言可以用來(lái)編寫(xiě)大型的復(fù)雜的應(yīng)用程序,成為企業(yè)級(jí)開(kāi)發(fā)語(yǔ)言。
概念
ES6 原生提供了 Promise 對(duì)象。
所謂 Promise,就是一個(gè)對(duì)象,用來(lái)傳遞異步操作的消息。它代表了某個(gè)未來(lái)才會(huì)知道結(jié)果的事件(通常是一個(gè)異步操作),并且這個(gè)事件提供統(tǒng)一的 API,可供進(jìn)一步處理。
Promise 對(duì)象有以下兩個(gè)特點(diǎn)。
(1)對(duì)象的狀態(tài)不受外界影響。Promise 對(duì)象代表一個(gè)異步操作,有三種狀態(tài):Pending(進(jìn)行中)、Resolved(已完成,又稱(chēng) Fulfilled)和 Rejected(已失敗)。只有異步操作的結(jié)果,可以決定當(dāng)前是哪一種狀態(tài),任何其他操作都無(wú)法改變這個(gè)狀態(tài)。這也是 Promise 這個(gè)名字的由來(lái),它的英語(yǔ)意思就是「承諾」,表示其他手段無(wú)法改變。
(2)一旦狀態(tài)改變,就不會(huì)再變,任何時(shí)候都可以得到這個(gè)結(jié)果。Promise 對(duì)象的狀態(tài)改變,只有兩種可能:從 Pending 變?yōu)?Resolved 和從 Pending 變?yōu)?Rejected。只要這兩種情況發(fā)生,狀態(tài)就凝固了,不會(huì)再變了,會(huì)一直保持這個(gè)結(jié)果。就算改變已經(jīng)發(fā)生了,你再對(duì) Promise 對(duì)象添加回調(diào)函數(shù),也會(huì)立即得到這個(gè)結(jié)果。這與事件(Event)完全不同,事件的特點(diǎn)是,如果你錯(cuò)過(guò)了它,再去監(jiān)聽(tīng),是得不到結(jié)果的。
有了 Promise 對(duì)象,就可以將異步操作以同步操作的流程表達(dá)出來(lái),避免了層層嵌套的回調(diào)函數(shù)。此外,Promise 對(duì)象提供統(tǒng)一的接口,使得控制異步操作更加容易。
Promise 也有一些缺點(diǎn)。首先,無(wú)法取消 Promise,一旦新建它就會(huì)立即執(zhí)行,無(wú)法中途取消。其次,如果不設(shè)置回調(diào)函數(shù),Promise 內(nèi)部拋出的錯(cuò)誤,不會(huì)反應(yīng)到外部。第三,當(dāng)處于 Pending 狀態(tài)時(shí),無(wú)法得知目前進(jìn)展到哪一個(gè)階段(剛剛開(kāi)始還是即將完成)。
var promise = new Promise(function(resolve, reject) { if (/* 異步操作成功 */){ resolve(value); } else { reject(error); } }); promise.then(function(value) { // success }, function(value) { // failure });
Promise 構(gòu)造函數(shù)接受一個(gè)函數(shù)作為參數(shù),該函數(shù)的兩個(gè)參數(shù)分別是 resolve 方法和 reject 方法。
如果異步操作成功,則用 resolve 方法將 Promise 對(duì)象的狀態(tài),從「未完成」變?yōu)椤赋晒Α梗磸?pending 變?yōu)?resolved);
如果異步操作失敗,則用 reject 方法將 Promise 對(duì)象的狀態(tài),從「未完成」變?yōu)椤甘 梗磸?pending 變?yōu)?rejected)。
基本的 api
Promise.resolve() Promise.reject() Promise.prototype.then() Promise.prototype.catch() Promise.all() // 所有的完成 var p = Promise.all([p1,p2,p3]); Promise.race() // 競(jìng)速,完成一個(gè)即可
進(jìn)階
promises 的奇妙在于給予我們以前的 return 與 throw,每個(gè) Promise 都會(huì)提供一個(gè) then() 函數(shù),和一個(gè) catch(),實(shí)際上是 then(null, ...) 函數(shù),
somePromise().then(functoin(){ // do something });
我們可以做三件事,
1. return 另一個(gè) promise
2. return 一個(gè)同步的值 (或者 undefined)
3. throw 一個(gè)同步異常 ` throw new Eror('');`
1. 封裝同步與異步代碼
``` new Promise(function (resolve, reject) { resolve(someValue); }); ```
寫(xiě)成
``` Promise.resolve(someValue); ```
2. 捕獲同步異常
new Promise(function (resolve, reject) { throw new Error('悲劇了,又出 bug 了'); }).catch(function(err){ console.log(err); });
如果是同步代碼,可以寫(xiě)成
Promise.reject(new Error("什么鬼"));
3. 多個(gè)異常捕獲,更加精準(zhǔn)的捕獲
somePromise.then(function() { return a.b.c.d(); }).catch(TypeError, function(e) { //If a is defined, will end up here because //it is a type error to reference property of undefined }).catch(ReferenceError, function(e) { //Will end up here if a wasn't defined at all }).catch(function(e) { //Generic catch-the rest, error wasn't TypeError nor //ReferenceError });
4. 獲取兩個(gè) Promise 的返回值
1. .then 方式順序調(diào)用
2. 設(shè)定更高層的作用域
3. spread
5. finally
任何情況下都會(huì)執(zhí)行的,一般寫(xiě)在 catch 之后
6. bind
somethingAsync().bind({}) .spread(function (aValue, bValue) { this.aValue = aValue; this.bValue = bValue; return somethingElseAsync(aValue, bValue); }) .then(function (cValue) { return this.aValue + this.bValue + cValue; });
或者 你也可以這樣
var scope = {}; somethingAsync() .spread(function (aValue, bValue) { scope.aValue = aValue; scope.bValue = bValue; return somethingElseAsync(aValue, bValue); }) .then(function (cValue) { return scope.aValue + scope.bValue + cValue; });
然而,這有非常多的區(qū)別,
- 你必須先聲明,有浪費(fèi)資源和內(nèi)存泄露的風(fēng)險(xiǎn)
- 不能用于放在一個(gè)表達(dá)式的上下文中
- 效率更低
7. all。非常用于于處理一個(gè)動(dòng)態(tài)大小均勻的 Promise 列表
8. join。非常適用于處理多個(gè)分離的 Promise
``` var join = Promise.join; join(getPictures(), getComments(), getTweets(), function(pictures, comments, tweets) { console.log("in total: " + pictures.length + comments.length + tweets.length); }); ```
9. props。處理一個(gè) promise 的 map 集合。只有有一個(gè)失敗,所有的執(zhí)行都結(jié)束
``` Promise.props({ pictures: getPictures(), comments: getComments(), tweets: getTweets() }).then(function(result) { console.log(result.tweets, result.pictures, result.comments); }); ```
10. any 、some、race
``` Promise.some([ ping("ns1.example.com"), ping("ns2.example.com"), ping("ns3.example.com"), ping("ns4.example.com") ], 2).spread(function(first, second) { console.log(first, second); }).catch(AggregateError, function(err) { err.forEach(function(e) { console.error(e.stack); }); });; ```
有可能,失敗的 promise 比較多,導(dǎo)致,Promsie 永遠(yuǎn)不會(huì) fulfilled
11. .map(Function mapper [, Object options])
用于處理一個(gè)數(shù)組,或者 promise 數(shù)組,
Option: concurrency 并發(fā)現(xiàn)
map(..., {concurrency: 1});
以下為不限制并發(fā)數(shù)量,讀書(shū)文件信息
var Promise = require("bluebird"); var join = Promise.join; var fs = Promise.promisifyAll(require("fs")); var concurrency = parseFloat(process.argv[2] || "Infinity"); var fileNames = ["file1.json", "file2.json"]; Promise.map(fileNames, function(fileName) { return fs.readFileAsync(fileName) .then(JSON.parse) .catch(SyntaxError, function(e) { e.fileName = fileName; throw e; }) }, {concurrency: concurrency}).then(function(parsedJSONs) { console.log(parsedJSONs); }).catch(SyntaxError, function(e) { console.log("Invalid JSON in file " + e.fileName + ": " + e.message); });
結(jié)果
$ sync && echo 3 > /proc/sys/vm/drop_caches $ node test.js 1 reading files 35ms $ sync && echo 3 > /proc/sys/vm/drop_caches $ node test.js Infinity reading files: 9ms
11. .reduce(Function reducer [, dynamic initialValue]) -> Promise
Promise.reduce(["file1.txt", "file2.txt", "file3.txt"], function(total, fileName) { return fs.readFileAsync(fileName, "utf8").then(function(contents) { return total + parseInt(contents, 10); }); }, 0).then(function(total) { //Total is 30 });
12. Time
.delay(int ms) -> Promise .timeout(int ms [, String message]) -> Promise
Promise 的實(shí)現(xiàn)
ASYNC
async 函數(shù)與 Promise、Generator 函數(shù)一樣,是用來(lái)取代回調(diào)函數(shù)、解決異步操作的一種方法。它本質(zhì)上是 Generator 函數(shù)的語(yǔ)法糖。async 函數(shù)并不屬于 ES6,而是被列入了 ES7。
以上就是本文的全部?jī)?nèi)容,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作能帶來(lái)一定的幫助,同時(shí)也希望多多支持腳本之家!
- 如何從零開(kāi)始利用js手寫(xiě)一個(gè)Promise庫(kù)詳解
- JS中promise化微信小程序api
- 淺談js promise看這篇足夠了
- JS 中使用Promise 實(shí)現(xiàn)紅綠燈實(shí)例代碼(demo)
- Javascript中Promise的四種常用方法總結(jié)
- JavaScript之promise_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理
- 大白話講解JavaScript的Promise
- JavaScript中Promise的使用詳解
- 淺談JavaScript中promise的使用
- 淺析Javascript ES6中的原生Promise
- Javascript Promise用法詳解
相關(guān)文章
微信小程序中獲取用戶(hù)手機(jī)號(hào)授權(quán)登錄詳細(xì)步驟
這篇文章主要給大家介紹了關(guān)于微信小程序中獲取用戶(hù)手機(jī)號(hào)授權(quán)登錄的詳細(xì)步驟,在微信小程序中開(kāi)發(fā)者可以通過(guò)微信提供的API接口實(shí)現(xiàn)用戶(hù)登錄和獲取用戶(hù)的手機(jī)號(hào),需要的朋友可以參考下2023-07-07用javascript動(dòng)態(tài)注釋掉HTML代碼
用javascript動(dòng)態(tài)注釋掉HTML代碼...2006-09-09聊聊Javascript中try catch的2個(gè)作用
try...catch 可以測(cè)試代碼中的錯(cuò)誤,try 部分包含需要運(yùn)行的代碼,而catch部分包含錯(cuò)誤發(fā)生時(shí)運(yùn)行的代碼,這篇文章主要給大家介紹了關(guān)于Javascript中try catch的2個(gè)作用,需要的朋友可以參考下2021-09-09基于JavaScript實(shí)現(xiàn)高德地圖和百度地圖提取行政區(qū)邊界經(jīng)緯度坐標(biāo)
本文給大家介紹javascript實(shí)現(xiàn)高德地圖和百度地圖提取行政區(qū)邊界經(jīng)緯度坐標(biāo)的相關(guān)知識(shí),本文實(shí)用性非常高,代碼簡(jiǎn)單易懂,需要的朋友參考下吧2016-01-01ES6使用 Array.includes 處理多重條件用法實(shí)例分析
這篇文章主要介紹了ES6使用 Array.includes 處理多重條件用法,結(jié)合實(shí)例形式分析了Array.includes基本功能、原理及處理多重條件相關(guān)操作技巧,需要的朋友可以參考下2020-03-03