Home > Web Front-end > JS Tutorial > body text

Tutorial on basic usage of Promise

小云云
Release: 2018-02-28 13:59:27
Original
3481 people have browsed it

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);
});
Copy after login

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);//可以使用异步操作中的数据
})
Copy after login

runAsync() After execution, the then method is called, then() is equivalent to what we wrote before callback function.

resolve and reject

function paramTest(){
    return new Promise((resolve, reject) => {
        let number = Math.ceil(Math.random() * 10);
        if (number < 5) {
            resolve(number);
        }else{
            reject(&#39;out of range&#39;);
        }
    })
}
paramTest().then((number) => {
    console.log('resolved');
    console.log(number);
},(reason) => {
    console.log('rejected');
    console.log(reason);
})
Copy after login

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

  • ##when

    number >= 5, we consider it a failure condition and change the status from pending to rejected

  • ##so
Execution result of paramTest()
:
fulfilledresolvednumbercatch usage
rejected
rejected
out of range

We continue to call

paramTest
method example<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">paramTest().then((number) =&gt; {     console.log('resolved');     console.log(number);     console.log(data); //data为未定义 },(reason) =&gt; {     console.log('rejected');     console.log(reason); }).catch((err) =&gt; {     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);
})
Copy after login

all
method receives an array parameter, and each item in the array returns a Promise object, only when p1, p2, p3 will not enter the then callback until they are all executed. p1, p2, p3 The returned data will be passed to the then 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) =&gt; {     setTimeout(() =&gt; {         resolve('p1');     }, 1000); }) .then(result =&gt; result) .catch(e =&gt; e); const p2 = new Promise((resolve, reject) =&gt; {     setTimeout(() =&gt; {         resolve('p2');     }, 3000); }) .then(result =&gt; result) .catch(e =&gt; e); Promise.all([p1, p2]) .then(result =&gt; console.log(result)) .catch(e =&gt; 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);
})
Copy after login

race
is exactly the same as all. The difference is that the all method requires parameters. then will be executed only if each item returns successfully; and race will execute the then 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.

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.race([p1, p2])
.then(result => console.log(result))
.catch(e => console.log(e));
//1秒后输出 'p1'
Copy after login
Click here to view the source code of the example in this article

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:


Use Promise to simplify callbacks

WeChat applet Promise is simplified Callback example sharing

How to use jQuery’s Promise correctly

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!