Table of Contents
1. Overview" >1. Overview
Promise Possible states: " >, these are the Promise Possible states:
Primitive functions (short: primitives) create atomic blocks. " >Primitive functions (short: primitives) create atomic blocks.
更实际工作上关于 .map()示例
Promise.all()的一个简版实现
5. Promise.race()" >5. Promise.race()
Promise.race() 在 Promise 超时下的情况
5.2 Promise.race() 的一个简版实现
6.Promise.allSettled()" >6.Promise.allSettled()
6.1 Promise.allSettled() 例子
6.2 Promise.allSettled() 较复杂点的例子
6.3 Promise.allSettled() 的简化实现
7. 短路特性" >7. 短路特性
8.并发性和 Promise.all()" >8.并发性和 Promise.all()
8.1 顺序执行与并发执行
8.2 并发技巧:关注操作何时开始
8.3 Promise.all() 与 Fork-Join 分治编程
Home Web Front-end JS Tutorial Understand the all(), race(), and allSettled() methods in Promise

Understand the all(), race(), and allSettled() methods in Promise

Dec 14, 2020 pm 05:48 PM
javascript promise

Understand the all(), race(), and allSettled() methods in Promise

Starting from ES6, we mostly use Promise.all() and Promise.race(), Promise. allSettled() The proposal has reached stage 4 and will therefore become part of ECMAScript 2020.

1. Overview

##Promise.all(promises: Iterable>): Promise> ;

    ##Promise.all(iterable)
  • method returns a Promise instance, this instance is iterable The callback is completed (resolve) when all promise in the parameters are "resolved" or the parameters do not contain promise; if promise in the parameters There is a failure (rejected), the callback of this instance fails (reject), the failure reason is the result of the first failed promise
Promise.race

(promises: Iterable>): Promise

##Promise.race(iterable)
    The method returns a
  • promise that will be resolved or rejected once a promise in the iterator is resolved or rejected. Promise.allSettled(promises: Iterable>): Promise>>

    Promise.allSettled() method returns a

    promise
      that
    • promise ##promise has been resolved or resolved after being rejected, and each object describes the outcome of each promise. 2. Review: Promise States
    • Given an asynchronous operation that returns a
    Promise

    , these are the Promise Possible states:

    pending: Initial state, neither success nor failure state. fulfilled: means the operation was completed successfully.

    rejected: means the operation failed.
    • Settled:
    • Promise
    • Either completed or rejected.
    • Promise
    • Once achieved, its status will no longer change.
    • 3. What is combination

    Understand the all(), race(), and allSettled() methods in Promise Also known as part-whole mode, it integrates objects into a tree structure to Represents a hierarchy of "part-whole" structures. The composition mode allows users to use single objects and composite objects consistently. It is based on two functions:

    Primitive functions (short: primitives) create atomic blocks.

    Composition functions (abbreviated as: composition) combine atoms and/or composites together to form composites.

      For JS Promises
    • The primitive functions include:
    • Promise.resolve()
    ,

    Promise.reject()

    • Combined functions: Promise.all(), Promise.race(),
    • Promise.allSettled()
    • 4. Promise.all()
    Type signature of Promise.all()

    :

    Promise.all(promises: Iterable<promise>>): Promise<array>><ul> <li><strong><t><t><t>##Return Situation: </t></t></t>Fulfillment: </strong></li>If the incoming iterable object is empty, </ul>Promise.all<p> will synchronously return a completed (</p>resolved<p>) status <strong>promise</strong>. <br>If all incoming <code>promise become completed, or there is no promise in the incoming iterable object, Promise.all returns
    promise Becomes fulfilled asynchronously. In any case, the completion status result of promise returned by Promise.all is an array, which contains the values ​​​​of all the incoming iteration parameter objects (including non-promise value).
    Failure/Rejection: If one of the incoming promise fails (

    rejected

    ), Promise.all Asynchronously gives the failed result to the callback function in the failure status, regardless of whether other
    promise are completed. Let’s take an example:

    1

    2

    3

    4

    5

    6

    7

    8

    9

    const promises = [

      Promise.resolve(&#39;a&#39;),

      Promise.resolve(&#39;b&#39;),

      Promise.resolve(&#39;c&#39;),

    ];

    Promise.all(promises)

      .then((arr) => assert.deepEqual(

        arr, [&#39;a&#39;, &#39;b&#39;, &#39;c&#39;]

      ));

    Copy after login
    What happens if one of the promises is rejected:

    1

    2

    3

    4

    5

    6

    7

    8

    9

    const promises = [

      Promise.resolve(&#39;a&#39;),

      Promise.resolve(&#39;b&#39;),

      Promise.reject(&#39;ERROR&#39;),

    ];

    Promise.all(promises)

      .catch((err) => assert.equal(

        err, &#39;ERROR&#39;

      ));

    Copy after login
    The following figure illustratesPromise.all()

    How it works

    4.1 Asynchronous.map() and Promise.all()Array conversion methods, such as

    .map( )

    , Understand the all(), race(), and allSettled() methods in Promise.filter()

    , etc., used for synchronous calculation. For example

    1

    2

    3

    4

    5

    6

    function timesTwoSync(x) {

      return 2 * x;

    }

    const arr = [1, 2, 3];

    const result = arr.map(timesTwoSync);

    assert.deepEqual(result, [2, 4, 6]);

    Copy after login

    What happens if the callback of

    .map() is a function based on Promise? Using this method, the result returned by .map()

    is an array of

    Promises.

    Promises数组不是普通代码可以使用的数据,但我们可以通过Promise.all()来解决这个问题:它将Promises数组转换为Promise,并使用一组普通值数组来实现。

    1

    2

    3

    4

    5

    6

    7

    8

    9

    function timesTwoAsync(x) {

      return new Promise(resolve => resolve(x * 2));

    }

    const arr = [1, 2, 3];

    const promiseArr = arr.map(timesTwoAsync);

    Promise.all(promiseArr)

      .then(result => {

        assert.deepEqual(result, [2, 4, 6]);

      });

    Copy after login

    更实际工作上关于 .map()示例

    接下来,咱们使用.map()Promise.all()Web下载文件。 首先,咱们需要以下帮助函数:

    1

    2

    3

    4

    5

    6

    7

    8

    9

    function downloadText(url) {

      return fetch(url)

        .then((response) => { // (A)

          if (!response.ok) { // (B)

            throw new Error(response.statusText);

          }

          return response.text(); // (C)

        });

    }

    Copy after login

    downloadText()使用基于Promise的fetch API 以字符串流的方式下载文件:

    • 首先,它异步检索响应(第A行)。
    • response.ok(B行)检查是否存在“找不到文件”等错误。
    • 如果没有错误,使用.text()(第C行)以字符串的形式取回文件的内容。

    在下面的示例中,咱们 下载了两个文件

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    const urls = [

      &#39;http://example.com/first.txt&#39;,

      &#39;http://example.com/second.txt&#39;,

    ];

     

    const promises = urls.map(

      url => downloadText(url));

     

    Promise.all(promises)

      .then(

        (arr) => assert.deepEqual(

          arr, [&#39;First!&#39;, &#39;Second!&#39;]

        ));

    Copy after login

    Promise.all()的一个简版实现

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    28

    29

    30

    31

    function all(iterable) {

      return new Promise((resolve, reject) => {

        let index = 0;

        for (const promise of iterable) {

          // Capture the current value of `index`

          const currentIndex = index;

          promise.then(

            (value) => {

              if (anErrorOccurred) return;

              result[currentIndex] = value;

              elementCount++;

              if (elementCount === result.length) {

                resolve(result);

              }

            },

            (err) => {

              if (anErrorOccurred) return;

              anErrorOccurred = true;

              reject(err);

            });

          index++;

        }

        if (index === 0) {

          resolve([]);

          return;

        }

        let elementCount = 0;

        let anErrorOccurred = false;

        const result = new Array(index);

      });

    }

    Copy after login

    5. Promise.race()

    Promise.race()方法的定义:

    Promise.race(promises: Iterable>): Promise

    Promise.race(iterable) 方法返回一个 promise,一旦迭代器中的某个promise解决或拒绝,返回的 promise就会解决或拒绝。来几个例子,瞧瞧:

    1

    2

    3

    4

    5

    6

    7

    8

    9

    const promises = [

      new Promise((resolve, reject) =>

        setTimeout(() => resolve(&#39;result&#39;), 100)), // (A)

      new Promise((resolve, reject) =>

        setTimeout(() => reject(&#39;ERROR&#39;), 200)), // (B)

    ];

    Promise.race(promises)

      .then((result) => assert.equal( // (C)

        result, &#39;result&#39;));

    Copy after login

    在第 A 行,Promise 是完成状态 ,所以 第 C 行会执行(尽管第 B 行被拒绝)。

    如果 Promise 被拒绝首先执行,在来看看情况是嘛样的:

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    const promises = [

      new Promise((resolve, reject) =>

        setTimeout(() => resolve(&#39;result&#39;), 200)),

      new Promise((resolve, reject) =>

        setTimeout(() => reject(&#39;ERROR&#39;), 100)),

    ];

    Promise.race(promises)

      .then(

        (result) => assert.fail(),

        (err) => assert.equal(

          err, &#39;ERROR&#39;));

    Copy after login

    注意,由于 Promse 先被拒绝,所以 Promise.race() 返回的是一个被拒绝的 Promise

    这意味着Promise.race([])的结果永远不会完成。

    下图演示了Promise.race()的工作原理:

    Understand the all(), race(), and allSettled() methods in Promise

    Promise.race() 在 Promise 超时下的情况

    在本节中,我们将使用Promise.race()来处理超时的 Promise。 以下辅助函数:

    1

    2

    3

    4

    5

    function resolveAfter(ms, value=undefined) {

      return new Promise((resolve, reject) => {

        setTimeout(() => resolve(value), ms);

      });

    }

    Copy after login

    resolveAfter() 主要做的是在指定的时间内,返回一个状态为 resolvePromise,值为为传入的 value

    调用上面方法:

    1

    2

    3

    4

    5

    6

    7

    function timeout(timeoutInMs, promise) {

      return Promise.race([

        promise,

        resolveAfter(timeoutInMs,

          Promise.reject(new Error(&#39;Operation timed out&#39;))),

      ]);

    }

    Copy after login

    timeout() 返回一个Promise,该 Promise 的状态取决于传入 promise 状态 。

    其中 timeout 函数中的 resolveAfter(timeoutInMs, Promise.reject(new Error(&#39;Operation timed out&#39;)) ,通过 resolveAfter 定义可知,该结果返回的是一个被拒绝状态的 Promise

    再来看看timeout(timeoutInMs, promise)的运行情况。如果传入promise在指定的时间之前状态为完成时,timeout 返回结果就是一个完成状态的 Promise,可以通过.then的第一个回调参数处理返回的结果。

    1

    2

    timeout(200, resolveAfter(100, &#39;Result!&#39;))

      .then(result => assert.equal(result, &#39;Result!&#39;));

    Copy after login

    相反,如果是在指定的时间之后完成,刚 timeout 返回结果就是一个拒绝状态的 Promise,从而触发catch方法指定的回调函数。

    1

    2

    timeout(100, resolveAfter(2000, &#39;Result!&#39;))

      .catch(err => assert.deepEqual(err, new Error(&#39;Operation timed out&#39;)));

    Copy after login

    重要的是要了解“Promise 超时”的真正含义:

    1. 如果传入入Promise 较到的得到解决,其结果就会给返回的 Promise
    2. 如果没有足够快得到解决,输出的 Promise 的状态为拒绝。

    也就是说,超时只会阻止传入的Promise,影响输出 Promise(因为Promise只能解决一次), 但它并没有阻止传入Promise的异步操作。

    5.2 Promise.race() 的一个简版实现

    以下是 Promise.race()的一个简化实现(它不执行安全检查)

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    function race(iterable) {

      return new Promise((resolve, reject) => {

        for (const promise of iterable) {

          promise.then(

            (value) => {

              if (settlementOccurred) return;

              settlementOccurred = true;

              resolve(value);

            },

            (err) => {

              if (settlementOccurred) return;

              settlementOccurred = true;

              reject(err);

            });

        }

        let settlementOccurred = false;

      });

    }

    Copy after login

    6.Promise.allSettled()

    “Promise.allSettled”这一特性是由Jason WilliamsRobert PamelyMathias Bynens提出。

    promise.allsettle()方法的定义:

    • Promise.allSettled(promises: Iterable<Promise>)
      : Promise<Array>>

    它返回一个ArrayPromise,其元素具有以下类型特征:

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    type SettlementObject<T> = FulfillmentObject<T> | RejectionObject;

     

    interface FulfillmentObject<T> {

      status: &#39;fulfilled&#39;;

      value: T;

    }

     

    interface RejectionObject {

      status: &#39;rejected&#39;;

      reason: unknown;

    }

    Copy after login

    Promise.allSettled()方法返回一个promise,该promise在所有给定的promise已被解析或被拒绝后解析,并且每个对象都描述每个promise的结果。

    举例说明, 比如各位用户在页面上面同时填了3个独立的表单, 这三个表单分三个接口提交到后端, 三个接口独立, 没有顺序依赖, 这个时候我们需要等到请求全部完成后给与用户提示表单提交的情况

    在多个promise同时进行时咱们很快会想到使用Promise.all来进行包装, 但是由于Promise.all的短路特性, 三个提交中若前面任意一个提交失败, 则后面的表单也不会进行提交了, 这就与咱们需求不符合.

    Promise.allSettledPromise.all类似, 其参数接受一个Promise的数组, 返回一个新的Promise, 唯一的不同在于, 其不会进行短路, 也就是说当Promise全部处理完成后我们可以拿到每个Promise的状态, 而不管其是否处理成功.

    下图说明promise.allsettle()是如何工作的

    Understand the all(), race(), and allSettled() methods in Promise

    6.1 Promise.allSettled() 例子

    这是Promise.allSettled() 使用方式快速演示示例

    1

    2

    3

    4

    5

    6

    7

    8

    Promise.allSettled([

      Promise.resolve(&#39;a&#39;),

      Promise.reject(&#39;b&#39;),

    ])

    .then(arr => assert.deepEqual(arr, [

      { status: &#39;fulfilled&#39;, value:  &#39;a&#39; },

      { status: &#39;rejected&#39;,  reason: &#39;b&#39; },

    ]));

    Copy after login

    6.2 Promise.allSettled() 较复杂点的例子

    这个示例类似于.map()Promise.all()示例(我们从其中借用了downloadText()函数):我们下载多个文本文件,这些文件的url存储在一个数组中。但是,这一次,咱们不希望在出现错误时停止,而是希望继续执行。Promise.allSettled()允许咱们这样做:

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    const urls = [

      &#39;http://example.com/exists.txt&#39;,

      &#39;http://example.com/missing.txt&#39;,

    ];

     

    const result = Promise.allSettled(

      urls.map(u => downloadText(u)));

    result.then(

      arr => assert.deepEqual(

        arr,

        [

          {

            status: &#39;fulfilled&#39;,

            value: &#39;Hello!&#39;,

          },

          {

            status: &#39;rejected&#39;,

            reason: new Error(&#39;Not Found&#39;),

          },

        ]

    ));

    Copy after login

    6.3 Promise.allSettled() 的简化实现

    这是promise.allsettle()的简化实现(不执行安全检查)

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    28

    29

    30

    31

    32

    33

    34

    35

    function allSettled(iterable) {

      return new Promise((resolve, reject) => {

        function addElementToResult(i, elem) {

          result[i] = elem;

          elementCount++;

          if (elementCount === result.length) {

            resolve(result);

          }

        }

     

        let index = 0;

        for (const promise of iterable) {

          // Capture the current value of `index`

          const currentIndex = index;

          promise.then(

            (value) => addElementToResult(

              currentIndex, {

                status: &#39;fulfilled&#39;,

                value

              }),

            (reason) => addElementToResult(

              currentIndex, {

                status: &#39;rejected&#39;,

                reason

              }));

          index++;

        }

        if (index === 0) {

          resolve([]);

          return;

        }

        let elementCount = 0;

        const result = new Array(index);

      });

    }

    Copy after login

    7. 短路特性

    Promise.all()romise.race() 都具有 短路特性

    • Promise.all(): 如果参数中 promise 有一个失败(rejected),此实例回调失败(reject)

    Promise.race():如果参数中某个promise解决或拒绝,返回的 promise就会解决或拒绝。

    8.并发性和 Promise.all()

    8.1 顺序执行与并发执行

    考虑下面的代码:

    1

    2

    3

    4

    5

    6

    7

    8

    asyncFunc1()

      .then(result1 => {

        assert.equal(result1, &#39;one&#39;);

        return asyncFunc2();

      })

      .then(result2 => {

        assert.equal(result2, &#39;two&#39;);

      });

    Copy after login

    使用.then()顺序执行基于Promise的函数:只有在 asyncFunc1()的结果被解决后才会执行asyncFunc2()

    Promise.all() 是并发执行的

    1

    2

    3

    4

    Promise.all([asyncFunc1(), asyncFunc2()])

      .then(arr => {

        assert.deepEqual(arr, [&#39;one&#39;, &#39;two&#39;]);

      });

    Copy after login

    8.2 并发技巧:关注操作何时开始

    确定并发异步代码的技巧:关注异步操作何时启动,而不是如何处理它们的Promises

    例如,下面的每个函数都同时执行asyncFunc1()asyncFunc2(),因为它们几乎同时启动。

    1

    2

    3

    4

    5

    6

    7

    8

    9

    function concurrentAll() {

      return Promise.all([asyncFunc1(), asyncFunc2()]);

    }

     

    function concurrentThen() {

      const p1 = asyncFunc1();

      const p2 = asyncFunc2();

      return p1.then(r1 => p2.then(r2 => [r1, r2]));

    }

    Copy after login

    另一方面,以下两个函数依次执行asyncFunc1()asyncFunc2(): asyncFunc2()仅在asyncFunc1()的解决之后才调用。

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    function sequentialThen() {

      return asyncFunc1()

        .then(r1 => asyncFunc2()

          .then(r2 => [r1, r2]));

    }

     

    function sequentialAll() {

      const p1 = asyncFunc1();

      const p2 = p1.then(() => asyncFunc2());

      return Promise.all([p1, p2]);

    }

    Copy after login

    8.3 Promise.all() 与 Fork-Join 分治编程

    Promise.all() 与并发模式“fork join”松散相关。重温一下咱们前面的一个例子:

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    Promise.all([

        // (A) fork

        downloadText(&#39;http://example.com/first.txt&#39;),

        downloadText(&#39;http://example.com/second.txt&#39;),

      ])

      // (B) join

      .then(

        (arr) => assert.deepEqual(

          arr, [&#39;First!&#39;, &#39;Second!&#39;]

        ));

    Copy after login

    • Fork:在A行中,分割两个异步任务并同时执行它们。
    • Join:在B行中,对每个小任务得到的结果进行汇总。

    英文原文:https://2ality.com/2019/08/promise-combinators.html

    更多编程相关知识,请访问:编程教学!!

The above is the detailed content of Understand the all(), race(), and allSettled() methods in Promise. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

Keeping your word: The pros and cons of delivering on your promises Keeping your word: The pros and cons of delivering on your promises Feb 18, 2024 pm 08:06 PM

In daily life, we often encounter problems between promises and fulfillment. Whether in a personal relationship or a business transaction, delivering on promises is key to building trust. However, the pros and cons of commitment are often controversial. This article will explore the pros and cons of commitments and give some advice on how to keep your word. The promised benefits are obvious. First, commitment builds trust. When a person keeps his word, he makes others believe that he is a trustworthy person. Trust is the bond established between people, which can make people more

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Learn more about Promise.resolve() Learn more about Promise.resolve() Feb 18, 2024 pm 07:13 PM

Detailed explanation of Promise.resolve() requires specific code examples. Promise is a mechanism in JavaScript for handling asynchronous operations. In actual development, it is often necessary to handle some asynchronous tasks that need to be executed in sequence, and the Promise.resolve() method is used to return a Promise object that has been fulfilled. Promise.resolve() is a static method of the Promise class, which accepts a

See all articles