Introducing ES6 promises

ES6 Promise is a programming mode introduced by ECMAScript 2015 (ES6 for short) to handle asynchronous operations. Promises can simplify asynchronous programming and make your code more maintainable. A Promise object represents an operation that has not yet been completed but is expected to complete in the future, and can track the state of this operation.

Promises have three states:

  1. Pending: The initial state, neither success nor failure.
  2. Fulfilled: Indicates that the operation completed successfully.
  3. Failed (rejected): Indicates that the operation failed or an error occurred.

The prototype of Promise provides thenand catchmethods to handle the callback functions of the successful and failed states respectively.

Here is an example of a basic usage of Promise:

// 创建一个 Promise
const promise = new Promise((resolve, reject) => {
  // 执行异步操作(例如:发起 Ajax 请求、读取文件等)
  setTimeout(() => {
    // 成功时执行 resolve 回调
    resolve('操作成功');
    // 发生错误时执行 reject 回调
    // reject('操作失败');
  }, 1000);
});

// 使用 then 方法处理成功状态
promise.then((result) => {
  console.log(result); // 输出 "操作成功"
});

// 使用 catch 方法处理失败状态
promise.catch((error) => {
  console.error(error); // 输出 "操作失败"
});

Promise also provides some static methods for handling multiple Promises, such as Promise.alland Promise.race.

  1. Promise.all: Receive an array containing multiple Promises, and return a new Promise when all Promises are fulfilled, and its resolve callback receives an array of resolve callback parameters for each successful Promise; if there is one or If multiple Promises fail (rejected), the new Promise enters the failed state, and the reject callback parameter of the first failed Promise is passed to the reject callback of the new Promise.

  2. Promise.race: Receive an array containing multiple Promises and return a new Promise. This new Promise will enter the corresponding state when the first input Promise is completed (whether it succeeds or fails), and its resolve or reject callback parameters are the same as The callback parameter of the first fulfilled Promise is the same.

Open source project address:

https://github.com/xutongbao/learn-chatgpt

Guess you like

Origin blog.csdn.net/xutongbao/article/details/130403968