当前位置:网站首页>Promise basic use
Promise basic use
2022-07-25 01:38:00 【"Rose has no principle"】
Catalog
instructions
promise Object can represent the success or failure of an asynchronous operation . What does that mean ? Is its state !
Here are three states :
- Waiting for the (pending): The initial state , Neither succeeded , And there was no failure .
- success (fulfilled): operation successfully done .
- Failure (rejected): operation failed .
Be careful : The state is an irreversible change , It will only change once ,promise The internal operation is synchronous .
Basis for instance
Now let's start to create a basic example to see , First, let's explain the parameters :
resolve: The status of this instance will be changed to fulfilled, And the passed in value will be given to the instance ;
reject: The status of this instance will be changed to rejected, And the passed in value will be given to the instance ;
// Create a simple instance
const promise = new Promise((resolve, reject) => { })
console.log(promise);The browser opens , give the result as follows :

PromiseState: On behalf of promise The state of , namely pending; Because the state of the instance is not changed at this time .
PromiseResult: On behalf of Promise Result , by undefined; Because no value is passed to the instance .
Basic applications
Now let's do a simple application and callback function , You can choose one of two callback methods :
// Create a 0-1 Random number between num, When num>=0.5 Judge as success, otherwise judge as failure
const promise = new Promise((resolve, reject) => {
const num = Math.random(0, 1)
if (num >= 0.5) {
resolve('ok')
} else {
reject('fail')
}
})
// Failed and successful callbacks ( Write together )
promise.then((onReslove) => {
// When the status is successful , Get into onReslove
console.log(onReslove);
}, (onRejected) => {
// When the status is failed , Get into onRejected
console.log(onRejected);
})
// Failed and successful callbacks ( Write separately )
promise.then((resolve) => {
// When the status is successful , Get into then
console.log(resolve);
}).catch((reject) => {
// When the status is failed , Get into catch
console.log(reject);
})
console.log(promise);Other methods
There are also several separate methods :
Promise.all([promise1,promise2,.....])
Parameters : contain n individual promise An array of objects
result : Every... In the array promise Object
Be careful : Only if all in the array promise When the objects are successful , The result is success ;
As long as there is a failure , The result is failure , And the value is the first failed promise The return value of the object ;
Promise.race([promise1,promise2,.....])
Parameters : contain n individual promise An array of objects
result : The first to change state promise Example
Promise.reject( )
The incoming parameter is Not promise object => The returned result is failed promise object , The value is the parameter passed in
The incoming parameter is promise object => The returned result is failed promise object , The value is passed in promise object
Is to pass everything is failure , The result is the incoming thing
Promise.resolve( )
The incoming parameter is Not promise object => The returned result is successful promise object , The value is the parameter passed in
The incoming parameter is promise object => The return result is determined by the result of the parameter resolve Result
边栏推荐
- Ecosystem long-term observation data product system
- Breederdao's first proposal was released: the constitution of the Dao organization
- The solution of displaying garbled code in SecureCRT
- Custom type
- Kubernetes creates a user with dashboard read-only permission (with exec permission)
- Ireport export PDF font bold failure
- Shell judges whether the file exists and whether the file size is 0
- Green low-carbon Tianyi cloud, a new engine of digital economy!
- Kernel structure and design
- If in ython__ name__ == ‘__ main__‘: Function and principle of
猜你喜欢

Pads copper laying

Implementing DDD based on ABP -- domain logic and application logic
![[development tutorial 10] crazy shell · open source Bluetooth smart health watch OTA image production and download technical documents](/img/97/c4ef281ca14eb68c8a14f18e03c3dd.png)
[development tutorial 10] crazy shell · open source Bluetooth smart health watch OTA image production and download technical documents

Custom type

Latex notes

Wireshark packet capturing and rapid packet location skills

Chip sold at sand price: Lei Jun's dream was "ruined" by this company

Fabric. JS centered element

EasyX realizes button effect

Summary of the most complete MySQL data types in history (Part 2)
随机推荐
[C + + primer notes] Chapter 6 functions
Join MotoGP Monster Energy British Grand Prix!
Amd epyc 9654 Genoa CPU cache test exposure L1 bandwidth up to 30tb/s
Kubernetes creates a user with dashboard read-only permission (with exec permission)
Worthington carboxyl transfer carbonic anhydrase application and literature reference
Install scoop and lux (formerly Annie)
[hero planet July training leetcode problem solving daily] 20th BST
[29. DFS depth is preferred]
C#/VB. Net insert watermark in word
Agreement on sharing agricultural scientific data in China
The current situation of the industry is disappointing. After working, I returned to UC Berkeley to study for a doctoral degree
Grpc sets connection lifetime and server health check
[26. String hash]
Cloud native platform, let edge applications play out!
Shell judges whether the file exists and whether the file size is 0
Safety management and application of genomic scientific data
ES6 modularization
Ireport export PDF font bold failure
Which bank outlet in Zhejiang can buy REITs fund products?
Fabric. JS centered element