使用 Promise 實現請求自動重試


使用 Promise 實現請求自動重試

"use strict";

/**
 *
 * @author xgqfrms
 * @license MIT
 * @copyright xgqfrms
 * @created 2020-11-20
 * @modified
 *
 * @description
 * @description
 * @difficulty Easy Medium Hard
 * @complexity O(n)
 * @time O(n)
 * @augments
 * @example
 * @link
 * @solutions
 *
 * @best_solutions
 *
 */

const log = console.log;


const autoRefetch = (url = ``, times = 3) => {
  const promise = fetch(url);
  promise.then(res => res.json(), err => {
    if(times > 0) {
      times -= 1;
      promise = fetch(url);
    }
  }).catch(err => {
    return Promise.reject(err);
  })
  return promise;
}


function maxRequest(url = ``, times = 3) {
  return new Promise((resolve, reject) => {
    if (times === 0) {
      reject('max request number')
      return
    }
    Promise.resolve(fetch(url)).then(value => {
      log(`OK`)
      resolve(value);
    }).catch(() => {
      log(`Error`)
      times -= 1;
      return maxRequest(url, times)
    })
  })
}

// function maxRequest(fn, maxNum) {
//   return new Promise((resolve, reject) => {
//     if (maxNum === 0) {
//       reject('max request number')
//       return
//     }
//     Promise.resolve(fn()).then(value => {
//       resolve(value)
//     }).catch(() => {
//       return maxRequest(fn, maxNum - 1)
//     })
//   })
// }


模擬 Promise.all & Promise.allSettled

Promise.all

要么全部 promise 結果都成功了,返回全部的 promise 構成的一個結果值的數組;
要么只要有一個 promise 失敗了,就返回失敗了的 promise 的 error 值,默認 undefined

一句話總結: 全部 promise 結果都成功了,返回一個有所有成功的結果值的數組; 只要有一個promise 失敗了,就的返回失敗結果;

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

PromiseAll = function(promises) {
    const values = [];
    let count = 0;
    return new Promise((resolve, reject) => {
        promises.forEach((promise, index) => {
            //  promise.then ? 強制轉換
            Promise.resolve(promise).then(res => {
                count += 1;
                values[index] = res;
                if (count === promises.length) {
                    resolve(values);
                }
            }, err => {
                reject(err);
            })
        })
    })
}

```js

// pending...


> Promise.allSettled 返回全部的 promise 的結果,無論 promise 結果是成功還是失敗,構成一個可迭代的數組對象

成功的 promise 返回一個有 status: 'fulfilled' 和 value 構成的對象
失敗的 promise 返回一個有 status: 'rejected' 和 reason 構成的對象

一句話總結: 無論 promise 是成功了還是失敗了, 最終都返回一個有 status 和 value 或 reason 構成的對象數組;

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/allSettled

```js

PromiseAllSellted = function(promises) {
    const result = [];
    let count = 0;
    return new Promise((resolve, reject) => {
        //  promise.then ? 強制轉換
        promises.forEach((promise, index) => {
            Promise.resolve(promise).then(res => {
                result[index] = {
                    status: `fullfilled`,
                    value: res,
                }
            }, err => {
                result[index] = {
                    status: `rejected`,
                    reason: err,
                }
            }).finally(() => {
                count++
                if (count === promises.length) {
                    resolve(result)
                }
            })
        })
    })
}

Promise.allSettled & Promise.all & Promise.race & Promise.any All In One

https://www.cnblogs.com/xgqfrms/p/13414614.html

refs



©xgqfrms 2012-2020

www.cnblogs.com 發布文章使用:只允許注冊用戶才可以訪問!



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM