Table of Contents
resolve and reject
We continue to call
Home Web Front-end JS Tutorial Tutorial on basic usage of Promise

Tutorial on basic usage of Promise

Feb 28, 2018 pm 01:59 PM
promise Instructions Tutorial

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Tutorial on how to use Dewu Tutorial on how to use Dewu Mar 21, 2024 pm 01:40 PM

Dewu APP is currently a very popular brand shopping software, but most users do not know how to use the functions in Dewu APP. The most detailed usage tutorial guide is compiled below. Next is the Dewuduo that the editor brings to users. A summary of function usage tutorials. Interested users can come and take a look! Tutorial on how to use Dewu [2024-03-20] How to use Dewu installment purchase [2024-03-20] How to obtain Dewu coupons [2024-03-20] How to find Dewu manual customer service [2024-03-20] How to check the pickup code of Dewu [2024-03-20] Where to find Dewu purchase [2024-03-20] How to open Dewu VIP [2024-03-20] How to apply for return or exchange of Dewu

How to use DirectX repair tool? Detailed usage of DirectX repair tool How to use DirectX repair tool? Detailed usage of DirectX repair tool Mar 15, 2024 am 08:31 AM

The DirectX repair tool is a professional system tool. Its main function is to detect the DirectX status of the current system. If an abnormality is found, it can be repaired directly. There may be many users who don’t know how to use the DirectX repair tool. Let’s take a look at the detailed tutorial below. 1. Use repair tool software to perform repair detection. 2. If it prompts that there is an abnormal problem in the C++ component after the repair is completed, please click the Cancel button, and then click the Tools menu bar. 3. Click the Options button, select the extension, and click the Start Extension button. 4. After the expansion is completed, re-detect and repair it. 5. If the problem is still not solved after the repair tool operation is completed, you can try to uninstall and reinstall the program that reported the error.

In summer, you must try shooting a rainbow In summer, you must try shooting a rainbow Jul 21, 2024 pm 05:16 PM

After rain in summer, you can often see a beautiful and magical special weather scene - rainbow. This is also a rare scene that can be encountered in photography, and it is very photogenic. There are several conditions for a rainbow to appear: first, there are enough water droplets in the air, and second, the sun shines at a low angle. Therefore, it is easiest to see a rainbow in the afternoon after the rain has cleared up. However, the formation of a rainbow is greatly affected by weather, light and other conditions, so it generally only lasts for a short period of time, and the best viewing and shooting time is even shorter. So when you encounter a rainbow, how can you properly record it and photograph it with quality? 1. Look for rainbows. In addition to the conditions mentioned above, rainbows usually appear in the direction of sunlight, that is, if the sun shines from west to east, rainbows are more likely to appear in the east.

What software is photoshopcs5? -photoshopcs5 usage tutorial What software is photoshopcs5? -photoshopcs5 usage tutorial Mar 19, 2024 am 09:04 AM

PhotoshopCS is the abbreviation of Photoshop Creative Suite. It is a software produced by Adobe and is widely used in graphic design and image processing. As a novice learning PS, let me explain to you today what software photoshopcs5 is and how to use photoshopcs5. 1. What software is photoshop cs5? Adobe Photoshop CS5 Extended is ideal for professionals in film, video and multimedia fields, graphic and web designers who use 3D and animation, and professionals in engineering and scientific fields. Render a 3D image and merge it into a 2D composite image. Edit videos easily

Tutorial on how to turn off the payment sound on WeChat Tutorial on how to turn off the payment sound on WeChat Mar 26, 2024 am 08:30 AM

1. First open WeChat. 2. Click [+] in the upper right corner. 3. Click the QR code to collect payment. 4. Click the three small dots in the upper right corner. 5. Click to close the voice reminder for payment arrival.

What is the KMS activation tool? How to use the KMS activation tool? How to use KMS activation tool? What is the KMS activation tool? How to use the KMS activation tool? How to use KMS activation tool? Mar 18, 2024 am 11:07 AM

The KMS Activation Tool is a software tool used to activate Microsoft Windows and Office products. KMS is the abbreviation of KeyManagementService, which is key management service. The KMS activation tool simulates the functions of the KMS server so that the computer can connect to the virtual KMS server to activate Windows and Office products. The KMS activation tool is small in size and powerful in function. It can be permanently activated with one click. It can activate any version of the window system and any version of Office software without being connected to the Internet. It is currently the most successful and frequently updated Windows activation tool. Today I will introduce it Let me introduce to you the kms activation work

Experts teach you! The Correct Way to Cut Long Pictures on Huawei Mobile Phones Experts teach you! The Correct Way to Cut Long Pictures on Huawei Mobile Phones Mar 22, 2024 pm 12:21 PM

With the continuous development of smart phones, the functions of mobile phones have become more and more powerful, among which the function of taking long pictures has become one of the important functions used by many users in daily life. Long screenshots can help users save a long web page, conversation record or picture at one time for easy viewing and sharing. Among many mobile phone brands, Huawei mobile phones are also one of the brands highly respected by users, and their function of cropping long pictures is also highly praised. This article will introduce you to the correct method of taking long pictures on Huawei mobile phones, as well as some expert tips to help you make better use of Huawei mobile phones.

PHP Tutorial: How to convert int type to string PHP Tutorial: How to convert int type to string Mar 27, 2024 pm 06:03 PM

PHP Tutorial: How to Convert Int Type to String In PHP, converting integer data to string is a common operation. This tutorial will introduce how to use PHP's built-in functions to convert the int type to a string, while providing specific code examples. Use cast: In PHP, you can use cast to convert integer data into a string. This method is very simple. You only need to add (string) before the integer data to convert it into a string. Below is a simple sample code

See all articles