亚洲视频二区_亚洲欧洲日本天天堂在线观看_日韩一区二区在线观看_中文字幕不卡一区

公告:魔扣目錄網(wǎng)為廣大站長(zhǎng)提供免費(fèi)收錄網(wǎng)站服務(wù),提交前請(qǐng)做好本站友鏈:【 網(wǎng)站目錄:http://www.430618.com 】, 免友鏈快審服務(wù)(50元/站),

點(diǎn)擊這里在線咨詢客服
新站提交
  • 網(wǎng)站:51998
  • 待審:31
  • 小程序:12
  • 文章:1030137
  • 會(huì)員:747

這篇文章算是 JAVAScript Promises 比較全面的教程,該文介紹了必要的方法,例如 then,catch和finally。此外,還包括處理更復(fù)雜的情況,例如與Promise.all并行執(zhí)行Promise,通過Promise.race 來處理請(qǐng)求超時(shí)的情況,Promise 鏈以及一些最佳實(shí)踐和常見的陷阱。

1.JavaScript Promises

Promise 是一個(gè)允許我們處理異步操作的對(duì)象,它是 es5 早期回調(diào)的替代方法。

與回調(diào)相比,Promise 具有許多優(yōu)點(diǎn),例如:

  • 讓異步代碼更易于閱讀。
  • 提供組合錯(cuò)誤處理。* 更好的流程控制,可以讓異步并行或串行執(zhí)行。

回調(diào)更容易形成深度嵌套的結(jié)構(gòu)(也稱為回調(diào)地獄)。如下所示:

a(() => {
  b(() => {
    c(() => {
      d(() => {
        // and so on ...
      });    });  });});

如果將這些函數(shù)轉(zhuǎn)換為 Promise,則可以將它們鏈接起來以生成更可維護(hù)的代碼。像這樣:

Promise.resolve()
  .then(a)
  .then(b)
  .then(c)
  .then(d)
  .catch(console.error);

在上面的示例中,Promise 對(duì)象公開了.then和.catch方法,我們稍后將探討這些方法。

1.1 如何將現(xiàn)有的回調(diào) API 轉(zhuǎn)換為 Promise?

我們可以使用 Promise 構(gòu)造函數(shù)將回調(diào)轉(zhuǎn)換為 Promise。

Promise 構(gòu)造函數(shù)接受一個(gè)回調(diào),帶有兩個(gè)參數(shù)resolve和reject。

  • Resolve:是在異步操作完成時(shí)應(yīng)調(diào)用的回調(diào)。
  • Reject:是發(fā)生錯(cuò)誤時(shí)要調(diào)用的回調(diào)函數(shù)。

構(gòu)造函數(shù)立即返回一個(gè)對(duì)象,即 Promise 實(shí)例。當(dāng)在 promise 實(shí)例中使用.then方法時(shí),可以在Promise “完成” 時(shí)得到通知。讓我們來看一個(gè)例子。

Promise 僅僅只是回調(diào)?

并不是。承諾不僅僅是回調(diào),但它們確實(shí)對(duì).then和.catch方法使用了異步回調(diào)。Promise 是回調(diào)之上的抽象,我們可以鏈接多個(gè)異步操作并更優(yōu)雅地處理錯(cuò)誤。來看看它的實(shí)際效果。

Promise 反面模式(Promises 地獄)

a(() => {
  b(() => {
    c(() => {
      d(() => {
        // and so on ...
      });    });  });});

不要將上面的回調(diào)轉(zhuǎn)成下面的 Promise 形式:

a().then(() => {
  return b().then(() => {
    return c().then(() => {
      return d().then(() =>{
        // ?? Please never ever do to this! ??
      });    });  });});

上面的轉(zhuǎn)成,也形成了 Promise 地獄,千萬(wàn)不要這么轉(zhuǎn)。相反,下面這樣做會(huì)好點(diǎn):

a()
  .then(b)
  .then(c)
  .then(d)

超時(shí)

你認(rèn)為以下程序的輸出的是什么?

const promise = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('time is up ?');
  }, 1e3);
  setTimeout(() => {
    reject('Oops ');
  }, 2e3);
});promise  .then(console.log)
  .catch(console.error);

是輸出:

time is up ?
Oops! 

還是輸出:

time is up ?

是后者,因?yàn)楫?dāng)一個(gè)Promise resolved 后,它就不能再被rejected。

一旦你調(diào)用一種方法(resolve 或reject),另一種方法就會(huì)失效,因?yàn)?promise 處于穩(wěn)定狀態(tài)。讓我們探索一個(gè) promise 的所有不同狀態(tài)。

1.2 Promise 狀態(tài)

Promise 可以分為四個(gè)狀態(tài):

  • ? Pending:初始狀態(tài),異步操作仍在進(jìn)行中。
  • ? Fulfilled:操作成功,它調(diào)用.then回調(diào),例如.then(onSuccess)。
  • ?? Rejected: 操作失敗,它調(diào)用.catch或.then的第二個(gè)參數(shù)(如果有)。例如.catch(onError)或.then(..., onError)。
  • Settled:這是 promise 的最終狀態(tài)。promise 已經(jīng)死亡了,沒有別的辦法可以解決或拒絕了。.finally方法被調(diào)用。
  •  
初學(xué)者應(yīng)該看的JavaScript Promise 完整指南

 

1.3 Promise 實(shí)例方法

Promise API 公開了三個(gè)主要方法:then,catch和finally。我們逐一配合事例探討一下。

Promise then

then方法可以讓異步操作成功或失敗時(shí)得到通知。它包含兩個(gè)參數(shù),一個(gè)用于成功執(zhí)行,另一個(gè)則在發(fā)生錯(cuò)誤時(shí)使用。

promise.then(onSuccess, onError);

你還可以使用catch來處理錯(cuò)誤:

promise.then(onSuccess).catch(onError);

Promise 鏈

then 返回一個(gè)新的 Promise ,這樣就可以將多個(gè)Promise 鏈接在一起。就像下面的例子一樣:

Promise.resolve()
  .then(() => console.log('then#1'))
  .then(() => console.log('then#2'))
  .then(() => console.log('then#3'));

Promise.resolve立即將Promise 視為成功。因此,以下所有內(nèi)容都將被調(diào)用。輸出將是

then#1
then#2
then#3

Promise catch

Promise .catch方法將函數(shù)作為參數(shù)處理錯(cuò)誤。如果沒有出錯(cuò),則永遠(yuǎn)不會(huì)調(diào)用catch方法。

假設(shè)我們有以下承諾:1秒后解析或拒絕并打印出它們的字母。

const a = () => new Promise((resolve) => setTimeout(() => { console.log('a'), resolve() }, 1e3));
const b = () => new Promise((resolve) => setTimeout(() => { console.log('b'), resolve() }, 1e3));
const c = () => new Promise((resolve, reject) => setTimeout(() => { console.log('c'), reject('Oops!') }, 1e3));
const d = () => new Promise((resolve) => setTimeout(() => { console.log('d'), resolve() }, 1e3));

請(qǐng)注意,c使用reject('Oops!')模擬了拒絕。

Promise.resolve()
  .then(a)
  .then(b)
  .then(c)
  .then(d)
  .catch(console.error)

輸出如下:

初學(xué)者應(yīng)該看的JavaScript Promise 完整指南

 

在這種情況下,可以看到a,b和c上的錯(cuò)誤消息。

我們可以使用then函數(shù)的第二個(gè)參數(shù)來處理錯(cuò)誤。但是,請(qǐng)注意,catch將不再執(zhí)行。

Promise.resolve()
  .then(a)
  .then(b)
  .then(c)
  .then(d, () => console.log('c errored out but no big deal'))
  .catch(console.error)
初學(xué)者應(yīng)該看的JavaScript Promise 完整指南

 

由于我們正在處理 .then(..., onError)部分的錯(cuò)誤,因此未調(diào)用catch。d不會(huì)被調(diào)用。如果要忽略錯(cuò)誤并繼續(xù)執(zhí)行Promise鏈,可以在c上添加一個(gè)catch。像這樣:

Promise.resolve()
  .then(a)
  .then(b)
  .then(() => c().catch(() => console.log('error ignored')))
  .then(d)
  .catch(console.error)

 

初學(xué)者應(yīng)該看的JavaScript Promise 完整指南

 

當(dāng)然,這種過早的捕獲錯(cuò)誤是不太好的,因?yàn)槿菀自谡{(diào)試過程中忽略一些潛在的問題。

Promise finally

finally方法只在 Promise 狀態(tài)是 settled 時(shí)才會(huì)調(diào)用。

如果你希望一段代碼即使出現(xiàn)錯(cuò)誤始終都需要執(zhí)行,那么可以在.catch之后使用.then。

Promise.resolve()
  .then(a)
  .then(b)
  .then(c)
  .then(d)
  .catch(console.error)
  .then(() => console.log('always called'));

或者可以使用.finally關(guān)鍵字:

Promise.resolve()
  .then(a)
  .then(b)
  .then(c)
  .then(d)
  .catch(console.error)
  .finally(() => console.log('always called'));

1.4 Promise 類方法

我們可以直接使用 Promise 對(duì)象中四種靜態(tài)方法。

  • Promise.all
  • Promise.reject
  • Promise.resolve
  • Promise.race

Promise.resolve 和 Promise.reject

這兩個(gè)是幫助函數(shù),可以讓 Promise 立即解決或拒絕。可以傳遞一個(gè)參數(shù),作為下次 .then 的接收:

Promise.resolve('Yay!!!')
  .then(console.log)
  .catch(console.error)

上面會(huì)輸出 Yay!!!

Promise.reject('Oops ')
  .then(console.log)
  .catch(console.error)

使用 Promise.all 并行執(zhí)行多個(gè) Promise

通常,Promise 是一個(gè)接一個(gè)地依次執(zhí)行的,但是你也可以并行使用它們。

假設(shè)是從兩個(gè)不同的api中輪詢數(shù)據(jù)。如果它們不相關(guān),我們可以使用Promise.all()同時(shí)觸發(fā)這兩個(gè)請(qǐng)求。

在此示例中,主要功能是將美元轉(zhuǎn)換為歐元,我們有兩個(gè)獨(dú)立的 API 調(diào)用。一種用于BTC/USD,另一種用于獲得EUR/USD。如你所料,兩個(gè) API 調(diào)用都可以并行調(diào)用。但是,我們需要一種方法來知道何時(shí)同時(shí)完成最終價(jià)格的計(jì)算。我們可以使用Promise.all,它通常在啟動(dòng)多個(gè)異步任務(wù)并發(fā)運(yùn)行并為其結(jié)果創(chuàng)建承諾之后使用,以便人們可以等待所有任務(wù)完成。

const axIOS = require('axios');
const bitcoinPromise = axios.get('https://api.coinpaprika.com/v1/coins/btc-bitcoin/markets');
const dollarPromise = axios.get('https://api.exchangeratesapi.io/latest?base=USD');
const currency = 'EUR';
// Get the price of bitcoins on
Promise.all([bitcoinPromise, dollarPromise])  .then(([bitcoinMarkets, dollarExchanges]) => {
    const byCoinbaseBtc = d => d.exchange_id === 'coinbase-pro' && d.pair === 'BTC/USD';
    const coinbaseBtc = bitcoinMarkets.data.find(byCoinbaseBtc)    const coinbaseBtcInUsd = coinbaseBtc.quotes.USD.price;    const rate = dollarExchanges.data.rates[currency];    return rate * coinbaseBtcInUsd;
  })  .then(price => console.log(`The Bitcoin in ${currency} is ${price.toLocaleString()}`))
  .catch(console.log)

如你所見,Promise.all接受了一系列的 Promises。當(dāng)兩個(gè)請(qǐng)求的請(qǐng)求都完成后,我們就可以計(jì)算價(jià)格了。

我們?cè)倥e一個(gè)例子:

const a = () => new Promise((resolve) => setTimeout(() => resolve('a'), 2000));
const b = () => new Promise((resolve) => setTimeout(() => resolve('b'), 1000));
const c = () => new Promise((resolve) => setTimeout(() => resolve('c'), 1000));
const d = () => new Promise((resolve) => setTimeout(() => resolve('d'), 1000));
console.time('promise.all');
Promise.all([a(), b(), c(), d()])  .then(results => console.log(`Done! ${results}`))
  .catch(console.error)
  .finally(() => console.timeEnd('promise.all'));

解決這些 Promise 要花多長(zhǎng)時(shí)間?5秒?1秒?還是2秒?

這個(gè)留給你們自己驗(yàn)證咯。

Promise race

Promise.race(iterable) 方法返回一個(gè) promise,一旦迭代器中的某個(gè)promise解決或拒絕,返回的 promise就會(huì)解決或拒絕。

const a = () => new Promise((resolve) => setTimeout(() => resolve('a'), 2000));
const b = () => new Promise((resolve) => setTimeout(() => resolve('b'), 1000));
const c = () => new Promise((resolve) => setTimeout(() => resolve('c'), 1000));
const d = () => new Promise((resolve) => setTimeout(() => resolve('d'), 1000));
console.time('promise.race');
Promise.race([a(), b(), c(), d()])  .then(results => console.log(`Done! ${results}`))
  .catch(console.error)
  .finally(() => console.timeEnd('promise.race'));

輸出是什么?

輸出 b。使用 Promise.race,最先執(zhí)行完成就會(huì)結(jié)果最后的返回結(jié)果。

你可能會(huì)問:Promise.race的用途是什么?

我沒胡經(jīng)常使用它。但是,在某些情況下,它可以派上用場(chǎng),比如計(jì)時(shí)請(qǐng)求或批量處理請(qǐng)求數(shù)組。

Promise.race([
  fetch('http://slowwly.robertomurray.co.uk/delay/3000/url/https://api.jsonbin.io/b/5d1fb4dd138da811182c69af'),
  new Promise((resolve, reject) => setTimeout(() => reject(new Error('request timeout')), 1000))
]).then(console.log)
.catch(console.error);
初學(xué)者應(yīng)該看的JavaScript Promise 完整指南

 

如果請(qǐng)求足夠快,那么就會(huì)得到請(qǐng)求的結(jié)果。

初學(xué)者應(yīng)該看的JavaScript Promise 完整指南

 

1.5 Promise 常見問題

串行執(zhí)行 promise 并傳遞參數(shù)

這次,我們將對(duì)Node的fs使用promises API,并將兩個(gè)文件連接起來:

const fs = require('fs').promises; // requires node v8+
fs.readFile('file.txt', 'utf8')
  .then(content1 => fs.writeFile('output.txt', content1))
  .then(() => fs.readFile('file2.txt', 'utf8'))
  .then(content2 => fs.writeFile('output.txt', content2, { flag: 'a+' }))
  .catch(error => console.log(error));

在此示例中,我們讀取文件1并將其寫入output 文件。稍后,我們讀取文件2并將其再次附加到output文件。如你所見,writeFile promise返回文件的內(nèi)容,你可以在下一個(gè)then子句中使用它。

如何鏈接多個(gè)條件承諾?

你可能想要跳過 Promise 鏈上的特定步驟。有兩種方法可以做到這一點(diǎn)。

const a = () => new Promise((resolve) => setTimeout(() => { console.log('a'), resolve() }, 1e3));
const b = () => new Promise((resolve) => setTimeout(() => { console.log('b'), resolve() }, 2e3));
const c = () => new Promise((resolve) => setTimeout(() => { console.log('c'), resolve() }, 3e3));
const d = () => new Promise((resolve) => setTimeout(() => { console.log('d'), resolve() }, 4e3));
const shouldExecA = true;
const shouldExecB = false;
const shouldExecC = false;
const shouldExecD = true;
Promise.resolve()  .then(() => shouldExecA && a())
  .then(() => shouldExecB && b())
  .then(() => shouldExecC && c())
  .then(() => shouldExecD && d())
  .then(() => console.log('done'))

如果你運(yùn)行該代碼示例,你會(huì)注意到只有a和d被按預(yù)期執(zhí)行。

另一種方法是創(chuàng)建一個(gè)鏈,然后僅在以下情況下添加它們:

const chain = Promise.resolve();
if (shouldExecA) chain = chain.then(a);
if (shouldExecB) chain = chain.then(b);
if (shouldExecC) chain = chain.then(c);
if (shouldExecD) chain = chain.then(d);
chain  .then(() => console.log('done'));

如何限制并行 Promise?

要做到這一點(diǎn),我們需要以某種方式限制Promise.all。

假設(shè)你有許多并發(fā)請(qǐng)求要執(zhí)行。如果使用 Promise.all 是不好的(特別是在API受到速率限制時(shí))。因此,我們需要一個(gè)方法來限制 Promise 個(gè)數(shù), 我們稱其為promiseAllThrottled。

// simulate 10 async tasks that takes 5 seconds to complete.
const requests = Array(10)
  .fill()  .map((_, i) => () => new Promise((resolve => setTimeout(() => { console.log(`exec'ing task #${i}`), resolve(`task #${i}`); }, 5000))));
promiseAllThrottled(requests, { concurrency: 3 })
  .then(console.log)
  .catch(error => console.error('Oops something went wrong', error));

輸出應(yīng)該是這樣的:

初學(xué)者應(yīng)該看的JavaScript Promise 完整指南

 

以上代碼將并發(fā)限制為并行執(zhí)行的3個(gè)任務(wù)。

實(shí)現(xiàn)promiseAllThrottled 一種方法是使用Promise.race來限制給定時(shí)間的活動(dòng)任務(wù)數(shù)量。

/**
 * Similar to Promise.all but a concurrency limit
 *
 * @param {Array} iterable Array of functions that returns a promise
 * @param {Object} concurrency max number of parallel promises running
 */
function promiseAllThrottled(iterable, { concurrency = 3 } = {}) {
  const promises = [];
  function enqueue(current = 0, queue = []) {
    // return if done
    if (current === iterable.length) { return Promise.resolve(); }
    // take one promise from collection
    const promise = iterable[current];
    const activatedPromise = promise();
    // add promise to the final result array
    promises.push(activatedPromise);
    // add current activated promise to queue and remove it when done
    const autoRemovePromise = activatedPromise.then(() => {
      // remove promise from the queue when done
      return queue.splice(queue.indexOf(autoRemovePromise), 1);
    });
    // add promise to the queue
    queue.push(autoRemovePromise);
    // if queue length >= concurrency, wait for one promise to finish before adding more.
    const readyForMore = queue.length < concurrency ? Promise.resolve() : Promise.race(queue);
    return readyForMore.then(() => enqueue(current + 1, queue));
  }
  return enqueue()
    .then(() => Promise.all(promises));
}

promiseAllThrottled一對(duì)一地處理 Promises 。它執(zhí)行Promises并將其添加到隊(duì)列中。如果隊(duì)列小于并發(fā)限制,它將繼續(xù)添加到隊(duì)列中。達(dá)到限制后,我們使用Promise.race等待一個(gè)承諾完成,因此可以將其替換為新的承諾。這里的技巧是,promise 自動(dòng)完成后會(huì)自動(dòng)從隊(duì)列中刪除。另外,我們使用 race 來檢測(cè)promise 何時(shí)完成,并添加新的 promise 。

人才們的 【三連】 就是小智不斷分享的最大動(dòng)力,如果本篇博客有任何錯(cuò)誤和建議,歡迎人才們留言,最后,謝謝大家的觀看。


作者:Adrian Mejia 譯者:前端小智 來源:adrianmjia

原文:https://adrianmejia.com/promises-tutorial-concurrency-in-javascript-node/

分享到:
標(biāo)簽:JavaScript Promise
用戶無(wú)頭像

網(wǎng)友整理

注冊(cè)時(shí)間:

網(wǎng)站:5 個(gè)   小程序:0 個(gè)  文章:12 篇

  • 51998

    網(wǎng)站

  • 12

    小程序

  • 1030137

    文章

  • 747

    會(huì)員

趕快注冊(cè)賬號(hào),推廣您的網(wǎng)站吧!
最新入駐小程序

數(shù)獨(dú)大挑戰(zhàn)2018-06-03

數(shù)獨(dú)一種數(shù)學(xué)游戲,玩家需要根據(jù)9

答題星2018-06-03

您可以通過答題星輕松地創(chuàng)建試卷

全階人生考試2018-06-03

各種考試題,題庫(kù),初中,高中,大學(xué)四六

運(yùn)動(dòng)步數(shù)有氧達(dá)人2018-06-03

記錄運(yùn)動(dòng)步數(shù),積累氧氣值。還可偷

每日養(yǎng)生app2018-06-03

每日養(yǎng)生,天天健康

體育訓(xùn)練成績(jī)?cè)u(píng)定2018-06-03

通用課目體育訓(xùn)練成績(jī)?cè)u(píng)定