Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the states of es6 promise

2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

Today, the editor will share with you the relevant knowledge about the state of es6 promise. The content is detailed and the logic is clear. I believe most people still know too much about this knowledge, so share this article for your reference. I hope you can get something after reading this article. Let's take a look at it.

There are three states: 1, pending, which indicates that the status is in progress and will be initialized; 2, fulfilled, which indicates success; and 3, rejected, which indicates that it has failed and triggers subsequent catch callback functions. After the state of promise is changed, it will solidify, it will not change again, and this result will be maintained all the time.

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

Introduction to Promise

Promise is a solution for asynchronous programming that is more reasonable and powerful than traditional solutions (callback functions and events).

A Promise is simply a container that holds the result of an event (usually an asynchronous operation) that ends in the future.

Syntactically, Promise is a constructor from which you can get messages for asynchronous operations.

Promise provides a unified API, and all kinds of asynchronous operations can be handled in the same way. With the Promise object, asynchronous operations can be expressed as a flow of synchronous operations, avoiding layers of nested callback functions.

The Promise object provides a unified interface that makes it easier to control asynchronous operations.

We know that es5 is a single-threaded language, and the order of sentence execution is from top to bottom, while ajax is needed when the front end of the project is connected to the back end, and ajax is asynchronous, which may lead to delay in the interaction of data, which is not conducive to programming. The promise function can solve this problem very well.

Promise instantiation

The Promise constructor takes a function as an argument whose arguments are resolve and reject. These two parameters are two functions provided by the JavaScript engine.

The Promise object represents an asynchronous operation with three states: pending (in progress), fulfilled (successful), and rejected (failed).

Initialization, status: pending

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

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

After the state changes, it solidifies, it will not change again, and the result will be maintained all the time, which is called resolved.

State change:

1. Pending-> resolved

2. Pending-> rejected

The expression of state

Pending status does not trigger then and catch

The resolved status triggers subsequent then callback functions

The rejected status triggers subsequent catch callback functions

Then and catch change state

Then normally returns resolved, and returns rejected if an error is reported.

Catch normally returns resolved, and returns rejected if an error is reported.

Const promise = new Promise (function (resolve,reject) {/ /... some code if (/ * asynchronous operation succeeded * /) {resolve (value); / / status changed from pending to fulfilled} else {reject (error); / / status changed from pending to rejected})

For example:

Test let promise = new Promise (function (resolve, reject) {if (3)

< 5) { resolve("是正确的"); } else { reject("是错误的"); } }) console.log(promise); 结果: Promise的原型方法 定义在Promise.prototype中的方法,通过Promise实例可以直接调用。 1、Promise.prototype.then() 当状态由pending变为fulfilled的时候执行该回调函数, 参数: 最多需要有两个参数,Promise 的成功和失败情况的回调函数。 返回值: 返回一个新的Promise实例对象,因此可以使用链式调用。 当一个 Promise 完成(fulfilled)或者失败(rejected)时,返回函数将被异步调用(由当前的线程循环来调度完成)。具体的返回值依据以下规则返回。如果 then 中的回调函数: 返回了一个值,那么 then 返回的 Promise 将会成为接受状态,并且将返回的值作为接受状态的回调函数的参数值。 没有返回任何值,那么 then 返回的 Promise 将会成为接受状态,并且该接受状态的回调函数的参数值为 undefined。 throw抛出一个错误,那么 then 返回的 Promise 将会成为拒绝状态,并且将抛出的错误作为拒绝状态的回调函数的参数值。 返回一个已经是接受状态的 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 ('success!') ; / / or / reject (new Error ("error!")) ;}); p1.then (value = > {console.log (value); / / success! }, error = > {console.log (error); / / error! ); 2. Promise.prototype.catch ()

Execute the callback function when the state changes from pending to rejected

Parameters:

Callback function. The parameter of the callback function is the value passed by reject function

Return value:

Returns a new Promise instance object, so you can use chained calls.

/ / throw an error that most of the time will call the catch method let p1 = new Promise (function (resolve, reject) {throw'Uhmurohcolors;}); p1.catch (function (e) {console.log (e); / / "Uh-oh!"})

It is recommended that you use the catch method instead of defining a callback function for the rejected state in the then method; this is because using catch can also catch errors in the execution of the then method.

/ / badpromise.then (function (data) {/ / success}, function (err) {/ / error}); / / goodpromise.then (function (data) {/ / success}) .catch (function (err) {/ / error}) 3, Promise.prototype.finally ()

The finally () method returns a Promise. At the end of the promise, the specified callback function is executed regardless of whether the result is fulfilled or rejected. This provides a way to execute code that needs to be executed after the Promise completes successfully or not. This avoids the need to write the same statement once in then () and once in catch ().

Parameters:

Callback function that does not receive any parameters

Return value:

Returns a new Promise instance object

Let p1 = new Promise (function (resolve, reject) {throw'Uhmurohlights;}); p1.catch (function (e) {console.log (e); / / "Uh-oh!"}) .finally (function () {console.log ('this code will eventually be executed');})

Promise encapsulates ajax request

Promise basically uses let promise = new Promise (function (resolve,reject) {/ / ajax to send an asynchronous request $.ajax ({/ / request path url:' http://47.100.84.201:8888/carousel/findAll',) / / successful callback success (res) {console.log ("successful callback", res) / / pass the successful callback through resolve / / resolve (res);}, / / failed callback error (err) {console.log ("failed callback", err) / / pass the failed callback through reject / / reject (err) }) / / manipulate the data through the instance method of the promise instance object promise. Then (res = > console.log ("receive data passed by resolve" + res)) .catch (err = > console.log ("receive data passed by reject" + err)) .finally (() = > {console.log ("it will be called regardless of success or failure!")})

Analysis: when using console.log ("successful callback", res) and console.log ("failed callback", err) in the two callback functions of ajax in the promise instance object When the statement reflects the result of the call (success or failure), the browser console does not execute the contents of the then\ catch\ finally method, because the then method does not receive whether the res,catch method from ajax received the err from ajax, so the statement in the arrow function is not executed.

When changed to resolve (res); and reject (err);, the results are as follows:

Promise level call

Suppose you have three files, first.txt,second.txt,third.txt, and read the file

The first way:

Use the normal way to read files at a hierarchical level (not recommended), as follows:

Const fs = require ("fs"); fs.readFile ('.. / FILE/first.txt', (err,data1) = > {fs.readFile ('.. / FILE/second.txt', (err,data2) = > {fs.readFile ('.. / FILE/second.txt', (err,data3) = > {let result = data1 +'\ t\ n' + data2 +'\ t\ n' + data3; console.log (result)) / /. / / if there are other files behind, it will lead to callback hell, the code will become very wide and long horizontally, and the data cannot be named again and again, so you need to keep taking names});});})

The second way:

Using promise implementation to solve indentation problems

Const fs = require ("fs"); / / initialize promise: read the first file, pass the data read out using the resolve function, and receive const promise = new Promise ((resolve,reject) = > {fs.readFile ('.. / FILE/first.txt', (err,data) = > {resolve (data)) with the Promise object. })}) / / execute the callback function promise.then (value = > {/ / first see if you can get the value / / console.log (value); / / output is buffer / / console.log (value.toString ()) / / you can use the toString method to convert buffer to a normal string / / the return value of the then method is a promise object So here we directly use return to return a promise object return new Promise ((resolve,reject) = > {/ / promise) the main operation is to read the contents of the file fs.readFile ('.. / FILE/second.txt', (err,data) = > {/ / pass the read data out, and here the read data is put into the array When / / value is sent out together, the contents of the file first.txt are read during initialization, and data refers to the file content resolve ([value,data]) currently read. })}) / / continue to call using chained calls Read the contents of the next file}) .then (value= > {return new Promise ((resolve,reject) = > {fs.readFile ('.. / FILE/third.txt', (err,data) = > {/ / add the read data to the array through the push method / / the value here is the array value.push (data) passed earlier) Resolve (value);})}) .then (value= > {/ / output the result of reading the file one by one console.log (value.toString ()); / / this is the first file, this is the second file, and this is the third file / / separated by commas})

Although it is true that there is a large amount of code using promise at present, it can avoid the problem of horizontal increase of code and will not affect code reading.

Static method

Methods defined in Promise can be called directly through Promise.

1. Promise.all ([p1memp2])

Promise.all is used to package multiple Promise instances into a new Promise instance

Parameters:

Array with elements in the array as Promise instances

Return value:

For a Promise instance, the status of the instance is fulfilled only when the status of p1Magi p2 is fulfilled. Then the return value of p1Magi p2 forms an array and is passed to the callback function of the instance. As long as one of the return values of p1Magi p2 becomes rejected, the status of the instance is rejected.

Const promise1 = Promise.resolve (3); / / this method is used to convert existing objects into Promise instances const promise2 = 42 resolve Const promise3 = new Promise ((resolve, reject) = > {setTimeout (resolve, 100, 'foo');}); Promise.all ([promise1, promise2, promise3]). Then ((values) = > {console.log (values);}); / / expected output: Array [3,42, "foo"] 2, Promise.race ([p1Med p2])

Promise.race is used to package multiple Promise instances into a new Promise instance

Parameters:

Array with elements in the array as Promise instances

Return value:

Promise instance, when one of the p1and p2 instances takes the lead in changing the state, the state of the instance changes accordingly. The return value of the Promise instance that is the first to change is passed to the callback function of that instance. (whoever executes it will return to him as soon as possible.)

Const promise1 = new Promise ((resolve, reject) = > {setTimeout (resolve, 500, 'one');}); const promise2 = new Promise ((resolve, reject) = > {setTimeout (resolve, 100,' two');}); Promise.race ([promise1, promise2]). Then ((value) = > {console.log (value); / / Both resolve, but promise2 is faster}) / / expected output: "two" 3, Promise.any ([p1memp2])

Used to package multiple Promise instances into a new Promise instance

Parameters:

Array with elements in the array as Promise instances

Return value:

For a Promise instance, as long as one of the p1 and p2 states changes to fulfilled, the instance status is changed from fulfilled;p1,p2 to rejected, and the instance status is rejected.

Const pErr = new Promise ((resolve, reject) = > {reject ("always fail"); const pSlow = new Promise ((resolve, reject) = > {setTimeout (resolve, 500, "finished");}); const pFast = new Promise ((resolve, reject) = > {setTimeout (resolve, 100, "done quickly");}); Promise.any ([pErr, pSlow, pFast]). Then ((value) = > {console.log (value)) / / pFast fulfils first}) / / expected output: "done quickly" 4. Promise.resolve ()

Used to convert existing objects to Promise instances

Parameters:

Arbitrary value

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

Returns a new Promise instance with a status of rejected.

Parameters:

Error message

Promise.reject (new Error ('fail')). Then (function () {/ / not called}, function (error) {console.log (error); / / Stacktrace}); that's all about the article "what are the states of es6 promise?" thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report