search
HomeWeb Front-endFront-end Q&Aes6 promise has several states

es6 promise has several states

May 19, 2022 pm 04:30 PM
es6promise

There are three states: 1. pending, which means it is in progress, and this state will be initialized; 2. fulfilled, which means it has been successful; 3. rejected, which means it has failed and will trigger the subsequent catch callback function. After the promise's status is changed, it will solidify and will not change again. This result will always be maintained.

es6 promise has several states

## The operating environment of this tutorial: Windows 7 system, ECMAScript version 6 , Dell G3 computer.

Introduction to Promise

Promise is a solution for

asynchronous programming, which is more reasonable and reasonable than traditional solutions (callback functions and events) More powerful.

The so-called Promise is simply a container that stores the result of an event (usually an asynchronous operation) that will end in the future.

Syntactically speaking, Promise is a constructor from which messages for asynchronous operations can be obtained.

Promise provides a unified API, and various asynchronous operations can be processed in the same way. With the Promise object, asynchronous operations can be expressed as a synchronous operation process, avoiding layers of nested callback functions.

Promise objects provide a unified interface, making it easier to control asynchronous operations.

We know that es5 is a single-threaded language, and the order of statement execution is from top to bottom. When the front end of the project is connected to the back end, ajax needs to be used, and ajax is asynchronous, which may lead to data interaction. Delay occurs, which is not conducive to programming. The promise function can solve this problem very well.

Promise instantiation

PromiseThe constructor accepts a function as a parameter, and the two parameters of the function are resolve and reject. And these two parameters are two functions, provided by the JavaScript engine.

The Promise object represents an asynchronous operation and has three states:

pending (in progress) , fulfilled (successful) and rejected (failed).

  • Initialization, status: pending

  • When resolve(successful) is called, status: pengding=>fulfilled

  • When reject (failed) is called, the status is: pending=>rejected

After the status changes, it solidifies and will not change again. This result will always be maintained. , then it is called

resolved(finalized).

Status changes:

1. pending -> resolved

2. pending -> rejected

State manifestation

  • The pending state will not trigger then and catch

  • The resolved state will trigger the subsequent then callback function

  • The rejected state will Trigger subsequent catch callback functions

then and catch change status

  • then will return resolved under normal circumstances, and rejected if an error occurs

  • catch will return resolved under normal circumstances, and rejected if an error occurs

  • const promise = new Promise(function(resolve,reject){
    	//...some code
    	if(/*异步操作成功*/){
    		resolve(value);
    		// 状态由pending变为fulfilled
    	}else{
    		reject(error);
    		// 状态由pending变为rejected
    	}
    })
For example:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>测试</title>
</head>
<body>
    <script>
        let promise = new Promise(function (resolve, reject) {
            if (3 < 5) {
                resolve("是正确的");
            } else {
                reject("是错误的");
            }
        })
        console.log(promise);
    </script>
</body>
</html>

Result:

es6 promise has several states

Prototype methods of Promise

The methods defined in

Promise.prototype can be called directly through Promise instances.

1. Promise.prototype.then()

This callback function is executed when the status changes from pending to fulfilled,

Parameters:

Requires at most two parameters, the callback function for success and failure of Promise.

Return value:

Returns a new Promise instance object, so

you can use chain calls .

When a Promise is fulfilled or rejected, the return function will be called asynchronously (scheduled by the current thread loop). The specific return value is returned according to the following rules. If the callback function in then:

  • returns a value, then the Promise returned by then will become the acceptance state, and the returned value will be used as the parameter value of the callback function that accepts the state.

  • If no value is returned, the Promise returned by then will become the acceptance state, and the parameter value of the callback function of the acceptance state is undefined.

  • throw throws an error, then the Promise returned by then will become the rejected state, and the thrown error will be used as the parameter value of the callback function in the rejected state.

  • 返回一个已经是接受状态的 Promise,那么 then 返回的 Promise 也会成为接受状态,并且将那个 Promise 的接受状态的回调函数的参数值作为该被返回的Promise的接受状态回调函数的参数值。

  • 返回一个已经是拒绝状态的 Promise,那么 then 返回的 Promise 也会成为拒绝状态,并且将那个 Promise 的拒绝状态的回调函数的参数值作为该被返回的Promise的拒绝状态回调函数的参数值。

  • 返回一个未定状态(pending)的 Promise,那么 then 返回 Promise 的状态也是未定的,并且它的终态与那个 Promise 的终态相同;同时,它变为终态时调用的回调函数参数与那个 Promise 变为终态时的回调函数的参数是相同的。

将上面的规则简单总结:
1、如果回调函数中的返回结果是promise对象,则对象状态由回调函数的执行结果决定
2、如果回到函数中的返回结果为非promise对象(无论是字符串、undefined…只要不是promise对象),对象状态均为成功,返回值为对象成功调用中的值。
3、throw抛出错误,状态为rejected

let p1 = new Promise((resolve, reject) => {
	resolve(&#39;成功!&#39;);
	// 或者
	// reject(new Error("出错了!"));
});

p1.then(value => {
	console.log(value); // 成功!
}, error => {
	console.log(error); // 出错了!
});

2、Promise.prototype.catch()

当状态由pending变为rejected的时候执行该回调函数,
参数:
回调函数,回调函数的参数为reject函数传递过来的值
返回值:
返回一个新的Promise实例对象,因此可以使用链式调用。

// 抛出一个错误,大多数时候将调用catch方法
let p1 = new Promise(function(resolve, reject) {
	throw &#39;Uh-oh!&#39;;
});

p1.catch(function(e) {
	console.log(e); // "Uh-oh!"
});

推荐使用catch方法,不要在then方法中定义rejected状态的回调函数;这是因为使用catch还可以捕获在then方法执行中存在的错误。

 // bad
promise.then(function(data) {
    // success
  }, function(err) {
    // error
  });

// good
promise.then(function(data) { 
    // success
  })
  .catch(function(err) {
    // error
  })

3、Promise.prototype.finally()

finally() 方法返回一个Promise。在promise结束时,无论结果是fulfilled或者是rejected,都会执行指定的回调函数。这为在Promise是否成功完成后都需要执行的代码提供了一种方式。这避免了同样的语句需要在then()和catch()中各写一次的情况。

参数:

回调函数,不接收任何参数

返回值:

返回一个新的Promise实例对象

let p1 = new Promise(function(resolve, reject) {
	throw &#39;Uh-oh!&#39;;
});
p1.catch(function(e) {
	console.log(e); // "Uh-oh!"
}).finally(function() { 
	console.log(&#39;这段代码最终都会执行&#39;); 
});
  • promise封装ajax请求
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <title>promise基本使用</title>
</head>
<body>
    <script>
        let promise = new Promise(function(resolve,reject){
            // ajax发送异步请求
            $.ajax({
                // 请求路径
                url:&#39;http://47.100.84.201:8888/carousel/findAll&#39;,
                // 成功回调
                success(res){
                    console.log("成功回调",res);
                    
                    // 通过resolve将成功的回调传递出去
                    //resolve(res);
                },
                // 失败回调
                error(err){
                    console.log("失败回调",err);
                    
                    // 通过reject将失败的回调传递出去
                    //reject(err);
                }
            })
        })

        // 通过promise实例对象的实例方法对数据进行操作
        promise
        .then(res => console.log("接收到resolve传递过来的数据" + res))
        .catch(err => console.log("接收reject传递的数据" + err))
        .finally(()=>{
            console.log("无论成功还是失败都会调用!")
        })
    </script> 
</body>
</html>

分析:当在promise实例对象中ajax的两个回调函数中使用console.log("成功回调",res)console.log("失败回调",err);语句反映调用结果(成功或失败)时,浏览器控制台并不会执行then\catch\finally方法中的内容,因为此时then方法中并没有接收到来自ajax的res,catch方法有没有接收到来自ajax的err,所以并不会执行箭头函数中的语句。
es6 promise has several states
当改为resolve(res);reject(err);时结果如下:
es6 promise has several states

  • promise层级调用
    假设有三个文件first.txt,second.txt,third.txt,读取文件
    第一种方式:
    使用普通方式进行层级读取文件(不推荐),如下:
const fs = require("fs");
fs.readFile(&#39;../FILE/first.txt&#39;,(err,data1) => {
    fs.readFile(&#39;../FILE/second.txt&#39;,(err,data2)=>{
        fs.readFile(&#39;../FILE/second.txt&#39;,(err,data3)=>{
            let result = data1 + &#39;\t\n&#39; + data2 + &#39;\t\n&#39; + data3;
            console.log(result);
            //...
            //如果后面还有其他文件呢,会导致回调地狱,代码会横向变得很宽很长,并且这里data不能重名,需要不断的取名字
        });
    });
});

第二种方式:

使用promise实现,解决缩进问题

const fs = require("fs");
// 初始化promise:读取第一个文件,使用resolve函数传递出去读取到的数据,用Promise对象接收
const promise = new Promise((resolve,reject)=>{
    fs.readFile(&#39;../FILE/first.txt&#39;,(err,data)=>{
        resolve(data);
    })
})

// 执行回调函数
promise.then(value => {
    //先看能不能获取到value值
    // console.log(value); //输出的是buffer
    // console.log(value.toString()); //可以使用toString方法转化buffer为正常字符串
   
    // then方法的返回值是一个promise对象,所以这里直接使用return返回一个promise对象
    return new Promise((resolve,reject)=>{
        // promise中的主要操作也是读取文件内容
        fs.readFile(&#39;../FILE/second.txt&#39;,(err,data)=>{
            // 将读取到的数据传递出去,这里将读取到的数据放到了数组中,一起传了出去
            // value是初始化时读取文件first.txt的内容,data指的是当前读到的文件内容
            resolve([value,data]);
        })
    })
    //使用链式调用方式继续调用,读取下一个文件的内容
}).then(value=>{
    return new Promise((resolve,reject)=>{
        fs.readFile(&#39;../FILE/third.txt&#39;,(err,data)=>{
            // 将读取到的data通过push方法添加进数组中
            // 这里的value是前面传过来的数组
            value.push(data);
            resolve(value);
        })
    })
}).then(value=>{
    // 输出一一读取文件后的结果
    console.log(value.toString()); // 这是第一个文件,这是第二个文件,这是第三个文件
    // 文件间通过逗号分隔
})

虽然目前使用promise的代码量确实比较多,但却可以避免代码横向增多的问题,不会影响代码阅读

静态方法

定义在Promise中的方法,通过Promise可以直接调用。

1、Promise.all([p1,p2])

Promise.all用于将多个 Promise 实例,包装成一个新的 Promise 实例
参数:
数组,数组中的元素为Promise实例
返回值:
Promise实例,当p1,p2状态都为fulfilled时候,该实例的状态才为fulfilled,此时p1,p2的返回值组成一个数组,传递给该实例的回调函数;只要p1,p2的返回值有一个变为rejected,该实例状态为rejected。

const promise1 = Promise.resolve(3); //该方法用于将现有对象转化为Promise实例
const promise2 = 42;
const promise3 = new Promise((resolve, reject) => {
	setTimeout(resolve, 100, &#39;foo&#39;);
});

Promise.all([promise1, promise2, promise3]).then((values) => {
	console.log(values);
});
// expected output: Array [3, 42, "foo"]

2、Promise.race([p1,p2])

Promise.race用于将多个 Promise 实例,包装成一个新的 Promise 实例
参数:
数组,数组中的元素为Promise实例
返回值:
Promise实例,当p1,p2之中有一个实例率先改变状态,该实例的状态就跟着改变。那个率先改变的 Promise 实例的返回值,就传递给该实例的回调函数。(谁执行的快就返回谁)

const promise1 = new Promise((resolve, reject) => {
		setTimeout(resolve, 500, &#39;one&#39;);
});

const promise2 = new Promise((resolve, reject) => {
	setTimeout(resolve, 100, &#39;two&#39;);
});

Promise.race([promise1, promise2]).then((value) => {
	console.log(value);
	// Both resolve, but promise2 is faster
});
// expected output: "two"

3、Promise.any([p1,p2])

用于将多个 Promise 实例,包装成一个新的 Promise 实例

参数:

数组,数组中的元素为Promise实例

返回值:

Promise实例,只要p1,p2状态有一个变为fulfilled,该实例的状态为fulfilledp1,p2状态都变为rejected,该实例状态才为rejected

const pErr = new Promise((resolve, reject) => {
	reject("总是失败");
});

const pSlow = new Promise((resolve, reject) => {
	setTimeout(resolve, 500, "最终完成");
});

const pFast = new Promise((resolve, reject) => {
	setTimeout(resolve, 100, "很快完成");
});

Promise.any([pErr, pSlow, pFast]).then((value) => {
	console.log(value);
	// pFast fulfils first
})
// expected output: "很快完成"

4、Promise.resolve()

用于将现有对象转化为Promise实例

参数:

任意值

const promise1 = Promise.resolve(123);
promise1.then((value) => {
	console.log(value);
	// expected output: 123
});

5、Promise.reject()

返回一个新的 Promise 实例,该实例的状态为rejected。

参数:

错误信息

Promise.reject(new Error(&#39;fail&#39;)).then(function() {
	// not called
}, function(error) {
	console.log(error); // Stacktrace
});

【相关推荐:javascript视频教程web前端

The above is the detailed content of es6 promise has several states. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
React: The Foundation for Modern Frontend DevelopmentReact: The Foundation for Modern Frontend DevelopmentApr 19, 2025 am 12:23 AM

React is a JavaScript library for building modern front-end applications. 1. It uses componentized and virtual DOM to optimize performance. 2. Components use JSX to define, state and attributes to manage data. 3. Hooks simplify life cycle management. 4. Use ContextAPI to manage global status. 5. Common errors require debugging status updates and life cycles. 6. Optimization techniques include Memoization, code splitting and virtual scrolling.

The Future of React: Trends and Innovations in Web DevelopmentThe Future of React: Trends and Innovations in Web DevelopmentApr 19, 2025 am 12:22 AM

React's future will focus on the ultimate in component development, performance optimization and deep integration with other technology stacks. 1) React will further simplify the creation and management of components and promote the ultimate in component development. 2) Performance optimization will become the focus, especially in large applications. 3) React will be deeply integrated with technologies such as GraphQL and TypeScript to improve the development experience.

React: A Powerful Tool for Building UI ComponentsReact: A Powerful Tool for Building UI ComponentsApr 19, 2025 am 12:22 AM

React is a JavaScript library for building user interfaces. Its core idea is to build UI through componentization. 1. Components are the basic unit of React, encapsulating UI logic and styles. 2. Virtual DOM and state management are the key to component work, and state is updated through setState. 3. The life cycle includes three stages: mount, update and uninstall. The performance can be optimized using reasonably. 4. Use useState and ContextAPI to manage state, improve component reusability and global state management. 5. Common errors include improper status updates and performance issues, which can be debugged through ReactDevTools. 6. Performance optimization suggestions include using memo, avoiding unnecessary re-rendering, and using us

Using React with HTML: Rendering Components and DataUsing React with HTML: Rendering Components and DataApr 19, 2025 am 12:19 AM

Using HTML to render components and data in React can be achieved through the following steps: Using JSX syntax: React uses JSX syntax to embed HTML structures into JavaScript code, and operates the DOM after compilation. Components are combined with HTML: React components pass data through props and dynamically generate HTML content, such as. Data flow management: React's data flow is one-way, passed from the parent component to the child component, ensuring that the data flow is controllable, such as App components passing name to Greeting. Basic usage example: Use map function to render a list, you need to add a key attribute, such as rendering a fruit list. Advanced usage example: Use the useState hook to manage state and implement dynamics

React's Purpose: Building Single-Page Applications (SPAs)React's Purpose: Building Single-Page Applications (SPAs)Apr 19, 2025 am 12:06 AM

React is the preferred tool for building single-page applications (SPAs) because it provides efficient and flexible ways to build user interfaces. 1) Component development: Split complex UI into independent and reusable parts to improve maintainability and reusability. 2) Virtual DOM: Optimize rendering performance by comparing the differences between virtual DOM and actual DOM. 3) State management: manage data flow through state and attributes to ensure data consistency and predictability.

React: The Power of a JavaScript Library for Web DevelopmentReact: The Power of a JavaScript Library for Web DevelopmentApr 18, 2025 am 12:25 AM

React is a JavaScript library developed by Meta for building user interfaces, with its core being component development and virtual DOM technology. 1. Component and state management: React manages state through components (functions or classes) and Hooks (such as useState), improving code reusability and maintenance. 2. Virtual DOM and performance optimization: Through virtual DOM, React efficiently updates the real DOM to improve performance. 3. Life cycle and Hooks: Hooks (such as useEffect) allow function components to manage life cycles and perform side-effect operations. 4. Usage example: From basic HelloWorld components to advanced global state management (useContext and

React's Ecosystem: Libraries, Tools, and Best PracticesReact's Ecosystem: Libraries, Tools, and Best PracticesApr 18, 2025 am 12:23 AM

The React ecosystem includes state management libraries (such as Redux), routing libraries (such as ReactRouter), UI component libraries (such as Material-UI), testing tools (such as Jest), and building tools (such as Webpack). These tools work together to help developers develop and maintain applications efficiently, improve code quality and development efficiency.

React and Frontend Development: A Comprehensive OverviewReact and Frontend Development: A Comprehensive OverviewApr 18, 2025 am 12:23 AM

React is a JavaScript library developed by Facebook for building user interfaces. 1. It adopts componentized and virtual DOM technology to improve the efficiency and performance of UI development. 2. The core concepts of React include componentization, state management (such as useState and useEffect) and the working principle of virtual DOM. 3. In practical applications, React supports from basic component rendering to advanced asynchronous data processing. 4. Common errors such as forgetting to add key attributes or incorrect status updates can be debugged through ReactDevTools and logs. 5. Performance optimization and best practices include using React.memo, code segmentation and keeping code readable and maintaining dependability

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment