In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly shows you "how to use ES6 Promise", the content is easy to understand, clear, hope to help you solve your doubts, the following let the editor lead you to study and learn "how to use ES6 Promise" this article.
What is Promise?
Promise is a solution of asynchronous programming, which is actually a constructor. It has all, reject, resolve methods on its own, and then, catch and other methods on the prototype. (ps: what is a prototype: https://www.yisu.com/article/231967.htm)
Promise objects have the following two characteristics.
(1) the state of the object is not affected by the outside world. The Promise object represents an asynchronous operation with three states: pending (in progress), fulfilled (successful), and rejected (failed). Only the result of the asynchronous operation can determine which state the current state is, and no other operation can change this state. This is the origin of the name Promise, which means "commitment" in English, indicating that other means cannot be changed.
(2) once the state changes, it will not change again, and this result can be obtained at any time. There are only two possibilities for a Promise object to change its state: from pending to fulfilled and from pending to rejected. As long as these two conditions occur, the state will solidify, will not change, and will maintain this result all the time, which is called resolved. If the change has already happened, you will get this result immediately if you add a callback function to the Promise object. This is completely different from the Event, which is characterized by the fact that if you miss it and listen again, you won't get a result.
Let's new a Promise first.
Let p = new Promise (function (resolve, reject) {/ / do some asynchronous operations setTimeout (function () {console.log ('execution completed Promise'); resolve (' data to be returned can be any data such as API return data');}, 2000);})
If you refresh the page, you will find that the console typed directly
The execution process is as follows: an asynchronous operation is performed, that is, after setTimeout,2 seconds, the output "execution complete" is output and the resolve method is called.
Be careful! I just new an object, and did not call it, we passed in the function has been executed, this is a detail to pay attention to. So when we use Promise, we usually wrap it in a function and run it when needed, such as:
Start asynchronous request const promiseClick = () = > {console.log ('click method called') let p = new Promise (function (resolve, reject) {/ / do some asynchronous operations setTimeout (function () {console.log ('execution completed Promise')) Resolve ('data to be returned can be any data such as data returned by API');}, 2000);}); return p}
There is no response when the page is refreshed, but it is typed on the console.
When placed in a function, it is executed only when it is called.
So, let's solve two problems next:
1. Why put it in the function
2. What the hell is resolve
At the end of our wrapped function, we return the Promise object, that is, we get a Promise object by executing this function. Then you can use the then and catch methods on the Promise object, which is the power of Promise. Take a look at the following code:
PromiseClick () .then (function (data) {console.log (data); / / other operations can be done later with the passed data / /.})
So the console output
First, the method is called to get up and execute promise, and finally the then method of promise is executed. The then method is a function that accepts a parameter that accepts the data returned by resolve, which outputs' the data to be returned can be any data such as the interface returns data'.
At this time, you should realize that the function in then has the same meaning as our usual callback function, which can be executed after the asynchronous task of promiseClick is completed. This is the function of Promise. To put it simply, it can separate the original callback writing method and execute the callback function by chain call after the asynchronous operation is executed.
You may think that this is no different from writing a callback function; what if there are multiple layers of callbacks? What if callback is also an asynchronous operation and needs a corresponding callback function after execution? You can't define another callback2 and send it to callback. The advantage of Promise is that you can continue to write the Promise object and return it in the then method, and then continue to call then for callback operations.
So: the essence is: Promise can only simplify the writing of layers of callbacks, but in essence, the essence of Promise is "state". The callback function can be called in time by maintaining and transferring state, which is much simpler and more flexible than passing callback function. So the correct scenario for using Promise is as follows:
PromiseClick () .then (function (data) {console.log (data); return runAsync2 ();}) .then (function (data) {console.log (data); return runAsync3 ();}) .then (function (data) {console.log (data);})
This allows you to output the contents of each asynchronous callback sequentially every two seconds, and the data passed to resolve in runAsync2 can be obtained in the next then method.
(Ps: this is performed many times because when I was studying the usage, I did it in the demo of a react. Multiple element changes on the page resulted in multiple rendering and execution of the page. If the normal page is rendered only once, all will only be executed once.)
The usage of reject
The above explains the resolve usage of promise, which means that resolve is a callback to the success of promise, which modifies the state of promise to
Fullfiled, then, reject is the callback in case of failure. He changes the state of promise to rejected so that we can capture it in then and then execute the callback of the "failed" situation.
Function promiseClick () {let p = new Promise (function (resolve, reject) {setTimeout (function () {var num = Math.ceil (Math.random () * 20)) / / generate 1-10 random numbers console.log ('value generated by random numbers:', num) if (num)
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.