This article mainly shares with you the basic usage tutorial of Promise. My personal understanding is to use synchronous programming to complete asynchronous programming operations. Hope it helps everyone.
const promise = new Promise((resolve, reject) => { //some asynchronous code setTimeout(() => { console.log('执行完成'); resolve('some data'); }, 2000); });
Promise
receives a function as a parameter. The function has two parameters, resolve
and reject
respectively represent the successful callback after the asynchronous operation is executed. functions and failure callback functions.
Promise
is executed immediately after instance. So usually a function is used to contain it
function runAsync() { return new Promise((resolve, reject) => { //some asynchronous code setTimeout(() => { console.log('执行完成'); resolve('some data'); }, 2000); }); } runAsync().then((data) => { console.log(data);//可以使用异步操作中的数据 })
runAsync()
After execution, the then
method is called, then()
is equivalent to what we wrote before callback function.
function paramTest(){ return new Promise((resolve, reject) => { let number = Math.ceil(Math.random() * 10); if (number < 5) { resolve(number); }else{ reject('out of range'); } }) } paramTest().then((number) => { console.log('resolved'); console.log(number); },(reason) => { console.log('rejected'); console.log(reason); })
Promise
have three states: pending
(in progress), fulfilled
(successful) and rejected
(failed)
paramTest()
Examples have two situations:
When number <5
, we consider it a success and change the status from pending
to fulfilled
number >= 5, we consider it a failure condition and change the status from
pending to
rejected
:
rejected | |
---|---|
rejected | |
out of range |
method example<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">paramTest().then((number) => {
console.log('resolved');
console.log(number);
console.log(data); //data为未定义
},(reason) => {
console.log('rejected');
console.log(reason);
}).catch((err) => {
console.log(err);
})</pre><div class="contentsignin">Copy after login</div></div>
catch The method is actually an alias of .then(null, rejection)
, It is also a callback function used to handle failures, but it also has another function: if an error occurs in the resolve
callback, it will not be blocked and the callback in catch
will be executed. Usage of all
const p = Promise.all([p1, p2, p3]); p.then(result => { console.log(result); })
method receives an array parameter, and each item in the array returns aPromise
object, only whenp1, p2, p3
will not enter thethen
callback until they are all executed.p1, p2, p3
The returned data will be passed to thethen
callback in the form of an array. The usage of<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">const p1 = new Promise((resolve, reject) => { setTimeout(() => { resolve('p1'); }, 1000); }) .then(result => result) .catch(e => e); const p2 = new Promise((resolve, reject) => { setTimeout(() => { resolve('p2'); }, 3000); }) .then(result => result) .catch(e => e); Promise.all([p1, p2]) .then(result => console.log(result)) .catch(e => console.log(e)); //3秒后输出['p1', 'p2']</pre><div class="contentsignin">Copy after login</div></div>
race
const p = Promise.race([p1, p2, p3]); p.then(result => { console.log(result); })
is exactly the same asall
. The difference is that theall
method requires parameters.then
will be executed only if each item returns successfully; andrace
will execute thethen
callback as long as one of the parameters returns successfully.The following is an example of
race. Compared with the
all
method, you can see that the return value is significantly different.Click here to view the source code of the example in this articleconst p1 = new Promise((resolve, reject) => { setTimeout(() => { resolve('p1'); }, 1000); }) .then(result => result) .catch(e => e); const p2 = new Promise((resolve, reject) => { setTimeout(() => { resolve('p2'); }, 3000); }) .then(result => result) .catch(e => e); Promise.race([p1, p2]) .then(result => console.log(result)) .catch(e => console.log(e)); //1秒后输出 'p1'Copy after login
resloader is a plug-in based on Promise that preloads images and displays the loading progress. Click here to learn more. If you feel it is okay, welcome to star
Related recommendations:
The above is the detailed content of Tutorial on basic usage of Promise. For more information, please follow other related articles on the PHP Chinese website!