Tutorial on basic usage of Promise
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.
resolve and reject
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 frompending
tofulfilled
- ##when
number >= 5
, we consider it a failure condition and change the status from
pendingto
rejected ##so
:
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) => {
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

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

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.

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.

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

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.

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

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 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
