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 is javascript Promise?

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

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces "what is javascript Promise". In daily operation, I believe many people have doubts about what javascript Promise is. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful for you to answer the doubts about "what is javascript Promise?" Next, please follow the editor to study!

What is Promise?

Promise is a solution for asynchronous programming that is more reasonable and powerful than traditional solutions-callback functions and events. It was first proposed and implemented by the community, and ES6 wrote it into the language standard, unified usage, and natively provided Promise objects.

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 an object 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.

The above is a definition of Promise, quoted from Ruan Yifeng's introduction to ES6 standards. Introduction to S6 standard. To say one more thing, the current JavaScript projects, whether foreground or backstage, should be written in the standard syntax of ES6. ES6 makes the writing of JavaScript more clear and standardized.

Basic usage

How to construct a promise object? native Promise is available in ES6.

Var promise = new Promise (function (resolve, reject) {/ /... Here is some code if (/ * Asynchronous operation succeeded * /) {resolve (value);} else {reject (error);}})

The above example shows the method of new a promise object. The constructor of Promise accepts a function as an argument. The two parameters of this function, reject and resolve, are the two functions provided by JavaScript itself. A promise object has three states, pending,resolved,rejected. The resolve function transforms the pending state to the resolved state. The reject function can say that the pending state changes from the rejected state. The state of the object is not affected by the outside world, which is also the origin of the name promise. On the outside, you hold a promise from me, and I will tell you my status later.

The promise object adds a callback function through the then method. Like this.

Promise.then (data= > console.log (data), err= > console.log (err))

When promise is resolved, the data log will be sent out. When promise is rejected, err will be log. It seems to be quite simple, but it is true that the use of Promise makes asynchronous operations appear in the form of synchronization. When an error occurs, you can define the callback function through the catch method.

How to use it

There are some dry definitions above, so how do you use it? how does Promise solve the problem? let's take a look at an example. Suppose that in the following scenario, we, a service, obtain data from an external service and write it to a db or a storage, and * is dragging out the stored status, then how is it written without promise? It could be like this.

GetData (function (value1) {storeToDb (value1, function (value2) {logStore (value2, function (value3) {/ /...});})

The traditional way of writing callbacks makes the code logic confused. If you think about it, if you add the situation of error handling, it will be even more sour. So what happens if you write in promise? Look at the code below.

Function getData () {return new Promise ((resolve,reject) = > {/ /... Send request to get data if (/ * get successfully*/) {resolve (data)} else {reject (err)})} function storeData (data) {return new Promise ((resolve,reject) = > {/ /. Store the data if (/ * store successfully*/) {resolve (data)} else {reject (err)})} getData () .then (data = > storeData (data)) .then (data = > console.log ('the process is done',data)); .catch (err = > console.error (' there is the err',err))

Is it very clear to write in this way? first getData, and then storeData,*** will log the operation, and any problems can be Catch out in catch. The logic of the code is reflected in a synchronous way. Let's take a look at how it would be written in other languages. Here is an example of ruby.

Def get_data / /... send request if / * get successfully * / return data else raise GetDataError end end def store_data / /... save to db if / * save successfully * / return data else raise StoreDataError end end / * Main Logic*/ begin request_data = get_data db_data = store_data request_data P "here is the store data # {db_data}" rescue e p "here is some errors # {e}" end

Comparing the two examples, we can see that the asynchronous programming mode of JavaScript is clearer and easier to understand after using Promise.

Because the execution environment of JavaScript is single-threaded, a large number of asynchronous programming is used, which makes it not very customary for us to write code. But with the emergence of Promise, this problem can be alleviated to some extent.

But the benefits of asynchronous operations, such as the example above, if we want to do 10 operations concurrently, that requires multiple threads to be started in ruby or other languages. But JavaScript doesn't have this problem at all. As long as a simple loop on it.

But what if we want to do something else based on the returned status after these 10 operations are completed? It is possible to use Promise.all at this time.

Let p = Promise.all ([p1, p2, p3])

Promise.all accepts an array as a parameter, and each element is a promise object. P will not be resolved until all the child promise are resolved. As long as one is rejected, the p will be rejected. But one thing is that there is no sequential relationship between these sub-promise. Let's look at another example:

Var guid = 0; function run () {guid++; var id = guid; return new Promise (resolve = > {setTimeout (function () {console.log (id); resolve (id);}, (Math.random () * 1.5 | 0) * 1000);});} var promises = Array.from ({length: 10}, run); Promise.all (promises)

OUTPUT:

2 3 5 6 7 8 10 1 4 9 at this point, the study of "what is javascript Promise" is over. I hope it can solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

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