Although the daily promise is not complicated, but the interview will inevitably be given some tricky Angle. There is also the fact that error capture processing has not been applied and understood. In order to fully understand promise, I wrote this article.
In fact, this article in MDN gives many examples, which are very vivid and concrete. Using_Promise said:
. , and catch(failureCallback) is short for then(null, failureCallback).
That is, you can think of catch as a “then” with only a second argument, in which case the following code makes sense.
new Promise((resolve, reject) => {
console.log('Initial');
resolve();
})
.then(() => {
throw new Error('Something failed');
console.log('Do this');
})
.catch(() => {
console.error('Do that');
})
.then(() => {
console.log('Do this, no matter what happened before');
});
Initial
Do that
Do this, no matter what happened before
Copy the code
P2’s second THEN is registered later than P1’s second THEN, but p1’s second THEN is executed first. It is not related to the registration order of the promise, but to the registration order of the promise.
setTimeout(() => console.log(0))
const p1 = new Promise((resolve) => {
console.log(1)
resolve(2)
console.log(3)
}).then(o => console.log(o))
const p2 = new Promise(resolve => {
console.log(4)
resolve(5)
}).then(o => console.log(o))
p2.then(() => console.log(6))
p1.then(() => console.log(7))
Copy the code
const p1 = new Promise(resolve => {
resolve(1);
}).then(data => console.log(data));
const p2 = new Promise(resolve => {
resolve(2)
}).then(data => console.log(data));
p2.then(data => {
console.log(3);
})
p2.then(data => {
console.log(4);
})
p1.then(data => {
console.log(5);
})
Copy the code
I feel like I still don’t fully understand promise, as I don’t quite understand the results of the following two pieces of code.
// const p1 = new Promise(resolve => {resolve(1); }).then(data => console.log(data)); const p2 = new Promise(resolve => { resolve(2) }).then(data => console.log(data)); p2.then(data => { console.log(3); }) p2.then(data => { console.log(4); }) p1.then(data => { console.log(5); }) // 1 2 5 3 4Copy the code
// const p1 = new Promise(resolve => {resolve(1); }); p1.then(data => console.log(data)); const p2 = new Promise(resolve => { resolve(2) }); p2.then(data => console.log(data)); p2.then(data => { console.log(3); }) p2.then(data => { console.log(4); }) p1.then(data => { console.log(5); }) // 1 2 3 4 5Copy the code