What is promise?
-
It is mainly used for asynchronous computing
-
Asynchronous operations can be queued, executed in the desired order, and returned as expected
-
Promises can be passed and manipulated between objects to help us deal with queues
Promise,
Create a promise
Promise to solve:
Get the results of asynchronous operations within a Promise using a. Then method, without blocking any programs that are not related to the Promise and allowing them to execute synchronously.
The then function returns a Promise instance, and the return value is a new instance rather than the previous one. Because the Promise specification states that states other than pending states cannot be changed, multiple THEN calls make no sense if the same instance is returned. For then, you can essentially think of it as a flatMap;
Promise state (lifecycle) :
-
Padding: In progress
-
This is very depressing
-
Rejected: It has failed
The completion of the asynchronous task depends on the current state of the Promise
1. This task will be fulfilled soon. 2
2. Call reject() Callback status: PADDing-> Rejected
Create a Promise method
Promise() creates a new Promise object. This constructor is primarily used to wrap functions that have not yet added promise support.
const myFirstPromise = new Promise((resolve, reject) = > {
/ /? Do some asynchronous operations and end up calling one of the following:
//
// resolve(someValue); // fulfilled
/ /? or
// reject("failure reason"); // rejected
});
Copy the code
Features of Promise:
1. The state of Promise is not affected by the outside world;
Because a Promise represents an asynchronous operation, only an asynchronous operation that succeeds or fails will change the * Promise state.
2. Once the state of Promise is changed, it cannot be changed;
Once the state is solidified, the returned result is called anywhere;
How promises are implemented:
A microtask that executes the Promise registration callback, whether it succeeds or fails; Microtask: it is equivalent to the emergency lane in high speed, which can make the microtask quickly line up at the front of the asynchronous queue, waiting for the main thread to call it through event polling;
Promise prototype approach
-
Promise.prototype.then() : The then() method handles whether a Promise is accepted or rejected.
-
Prototype. Catch () : then(undefined, onRejected)
-
Promise. Prototype. Finally () : the finally () method at the end of the Promise, no matter the result is fulfilled or is rejected, will implement the callback function
/* * Promise.prototype * then: Set the method to execute on success or failure (both can be set, Then ([success], [error]) * pro. Then ([success]) * pro. Then (null, [error]) * Catch: Set the method to execute on success or failure (usually not) */
new Promise(function (resolve, reject) {
console.log('I'm the sync callback for Promise.');
// Asynchronous tasks
$.ajax({
url:'./data.json'.success:function (data) {
// console.log(data)
resolve(data) / / success
},
error:function (err) {
reject(err) / / fail
}
})
}
).then(
(res) = > {
console.log(res)
console.log( simpleArray(res))
}, / / success
(err) = > {console.log(err)} / / fail
).catch(error= > {
console.log('Failure:' + error);
}).finally(x= > {
console.log('ha ha');
});
console.log('I'm sync code')
function simpleArray (data) {
return data.map(function (item) {
// console.log(item)
return item.name
})
}
// I'm the sync callback for Promise
// I am synchronous code
// ["zhangsan", "lisi", "wangwu"]
/ / ha ha
Copy the code
Static method for Promise:
-
Promise.resolve(value): Returns a Promise of a successful state, and registers the successful callback through.then();
-
Promse.reject(value): Returns a failed state Promise, registering the failed callback with.catch();
-
Promise.all([p1,p2,p3]): Only if all the Promise objects in the set succeed, will return a result and an array;
-
Promise.race([P1, P2,p3]): returns one of the fastest results;
-
Promise.any([P1,p2,p3]) : Receives a set of Promise objects, and returns the value of that successful Promise when one of them succeeds.
Promise.all()
/ / chopping vegetables
function cutUp(){
console.log('Start chopping. ');
var p = new Promise(function(resolve, reject){ // Do some asynchronous operations
setTimeout(function(){
console.log('Chopping is over! ');
resolve('Cut vegetables');
}, 1000);
});
return p;
}
/ / boiling water
function boil(){
console.log('Start boiling water. ');
var p = new Promise(function(resolve, reject){ // Do some asynchronous operations
setTimeout(function(){
console.log('Boil the water! ');
resolve('Boiled water');
}, 1000);
});
return p;
}
Promise.all([cutUp(), boil()])
.then((result) = > {
console.log('All ready');
console.log(result);
})
// Start chopping.
// Start boiling water.
//Promise {<pending>}
// The chopping is over!
// The water is boiling!
// All the preparations are completed
//[" cut vegetables ", "boiled water "]
Copy the code
Promise.race()
let p1 = new Promise(resolve= > {
setTimeout(() = > {
resolve('I\`m p1 ')},1000)});let p2 = new Promise(resolve= > {
setTimeout(() = > {
resolve('I\`m p2 ')},2000)});Promise.race([p1, p2])
.then(value= > {
console.log(value)
})
//I`m p1
Copy the code
Promise is compatible with
Use promise-polyfill to resolve compatibility issues
Promise – polyfill resources address: www.npmjs.com/package/pro…