This is the second day of my participation in the August More text Challenge. For details, see:August is more challenging
Promise FAQ summary
1, a brief introduction to Promise.
Promise is an asynchronous programming solution that is more rational and powerful than the traditional solution of callbacks and events. Solving the problem of callback hell, the essence of a Promise is “state”, which is much simpler and more flexible than passing callback functions by maintaining and passing state.
This is very sad, very sad, very sad, very sad, very sad
2. Implement a simple Promsie class that supports asynchronous chained calls.
let p = new Promsie((resolve,reject) = >{
let num = Math.ceil(Math.random()*10)
if (num <= 5) {
resolve(num)
}else {
reject('The number is too big.')
}
})
p.then(data= >console.log(data)).catch(err= >console.error(err))
Copy the code
3, the order in which promise. then is executed in the Event Loop.
There are two types of tasks in JS: macro tasks and micro tasks. Microtask execution takes precedence over macro task execution because microtask execution takes place before DOM rendering and macro task execution takes place after DOM rendering.
4. Explain some static methods of Promsie.
All, promise. race, promise. resolve, promsie. reject, etc.
Promise. All usage
Who runs slowly, who shall prevail to execute the callback. All takes an array argument, the values of which are eventually returned as Promise objects.
// Promise's all method provides the ability to perform asynchronous operations in parallel and not execute the callback until all asynchronous operations have been completed
let Promise1 = new Promise((resolve,reject) = >{})
let Promise2 = new Promise((resolve,reject) = >{})
let Promise3 = new Promise((resolve,reject) = >{})
let p = Promsie.all([Promise1,Promise2,Promise3])
p
.then(() = >console.log('All three'))
.catch(() = >console.log('failure'))
Copy the code
Promise. The use of the race
The one who runs fast is the one who will execute the callback.
For example, we can use race to set a timeout period for an asynchronous request and perform the corresponding operation after the timeout.
// Request an image resource
function requestImg(){
let p = new Promise((resolve,reject) = >{
let img = new Image();
img.onload = function() {
resolve(img);
}
img.src = 'Path to the picture'});return p;
}
// The delay function is used to time the request
function timeout(){
let p = new Promise((resolve,reject) = >{
setTimeout(() = >{
reject('Image request timeout');
},5000)});return p;
}
Promise.race([requestImg(),timeout()])
.then(data= >console.log(data))
.catch(err= >console.log(err))
Copy the code
5. What are the disadvantages of Promise?
- 1. You cannot cancel a Promise. Once a Promise is created, it is executed immediately.
- If the callback function is not set, the Promise will throw an error that is not reflected externally.
- Errors can only be handled sequentially. Even if a catch method is added at the end of the Promise chain, there may still be errors that cannot be caught.
- 4, reading the code is not easy to understand, you will see a bunch of then, you have to figure out the logic in the then callback function.
6, use Promise for sequential processing
It is recommended to use async functions with await mode or array.prototype. reduce implementation
- Use the async function
function getResult(){
async function queue(arr) {
let res = []
for (let fn of arr) {
var data= await fn();
res.push(data);
}
return await res
}
queue([getA,getB])
.then(data= > {
return addAB(data[0],data[1])
}).then(data= >console.log(data))
}
Copy the code
- The use of Array. The prototype. Reduce
function runPromiseInSequence(arr, input) {
return arr.reduce(
(promiseChain, currentFunction) = > promiseChain.then(currentFunction),
Promise.resolve(input)
);
}
// promise function 1
function p1(a) {
return new Promise((resolve, reject) = > {
resolve(a * 5);
});
}
// promise function 2
function p2(a) {
return new Promise((resolve, reject) = > {
resolve(a * 2);
});
}
// function 3 - will be wrapped in a resolved promise by .then()
function f3(a) {
return a * 3;
}
// promise function 4
function p4(a) {
return new Promise((resolve, reject) = > {
resolve(a * 4);
});
}
const promiseArr = [p1, p2, f3, p4];
runPromiseInSequence(promiseArr, 10)
.then(console.log); / / 1200
Copy the code
How to stop a Promise chain?
Add a method at the end of the promise chain that returns a promise that never executes resolve or Reject. The promsie is always pending, so no further THEN or catch is executed. This stops a promise chain.
Promsie.stop = function() {
return new Promsie(function(){})}Copy the code
8. What if the last Promise on the Promise chain goes wrong?
We all know that catch methods are called at the end of a promise chain to catch errors in the chain, but catch methods can also have errors inside of them, so we can add a done method to a Promise implementation. Done provides an error-free catch method. It no longer returns a promise and can be used to end a promise chain.
done() {
this.catch(reason= > {
console.log('done', reason);
throw reason;
});
}
Copy the code
9. What are Promise use techniques or best practices?
- 1. Chained promsie should return a promise, not just construct one.
- 2, reasonable use promise. all and promise. race and other methods.
- 3. Reject the then method, reject the promsise error, and add a catch to the end. If the catch() code fails again, add the done() function to the end of the call.
The last
There are a lot of data about Promise, Promise is the most important asynchronous programming, finally hope you can master Promise~
⚽ This article introduces common knowledge and solutions to some common problems ~ ⚾ If this article is helpful to you, please click the like to collect ~ 🏀GitHub blog: github.com/Awu1227. 🏉 I have other columns, welcome to read ~ 🎱Vue from give up to get Started 🏐 play with the Beauty of CSS 🎳 Easy JavaScript