This is the twenty-seventh day since I participated in Gwen Challenge
What is a Promise
Promise is an asynchronous programming solution!
- The current event cycle doesn’t give you results, but future events will give you results
- It’s a state machine
- pengding
- resolved
- reejectd
What does the state flow look like from the code
Pending to resolve flow test
(function () {
const res = new Promise((resolve, reject) = > {
setTimeout(() = > {
resolve();
}, 500);
});
console.log("500ms", res);
setTimeout(() = > {
console.log("800ms", res);
}, 800); }) ();Copy the code
Print the following information
The result is in line with our expectations
- We don’t have immediate access
promise
At this timepromise
In apending
state - You must wait a certain amount of time before retrieving it
promise
At this timepromise
In afulfilled
state
Pending to Reject flow tests
(function () {
const res = new Promise((resolve, reject) = > {
setTimeout(() = > {
reject(new Error("error"));
}, 500);
});
console.log("500ms", res);
setTimeout(() = > {
console.log("800ms", res);
}, 800); }) ();Copy the code
Print the following information
The result is in line with our expectations
- We don’t have immediate access
promise
At this timepromise
In apending
state - You must wait a certain amount of time before retrieving it
promise
At this timepromise
In areject
state
Note: If a pengding state is rejected and the error is not caught properly, it is thrown into the JS global
The reslove state is transferred to reject state test
(function () {
const res = new Promise((resolve, reject) = > {
setTimeout(() = > {
resolve();
}, 300);
setTimeout(() = > {
reject(new Error("error"));
}, 500);
});
console.log("500ms", res);
setTimeout(() = > {
console.log("800ms", res);
}, 800); }) ();Copy the code
Print the following information
You can see it!
At 300ms, promise switched to resolve and never reached reject
pending
Can only be transferred toresolve
orreject
;resolve
和reject
They can’t flow to each other;
Use then,catch to catch the result of a promise
(function () {
const res = new Promise((resolve, reject) = > {
setTimeout(() = > {
resolve(3);
}, 300);
})
.then((result) = > {
console.log("result", result);
})
.catch((error) = > {
console.log("error", error);
});
console.log("300ms", res);
setTimeout(() = > {
console.log("800ms", res);
}, 800); }) ();Copy the code
Print the following information
You can find
then
是promise
State flow toreslove
State available results
(function () {
const res = new Promise((resolve, reject) = > {
setTimeout(() = > {
reject(new Error("error-3"));
}, 300);
})
.then((result) = > {
console.log("result", result);
})
.catch((error) = > {
console.log("error", error);
});
console.log("300ms", res);
setTimeout(() = > {
console.log("800ms", res);
}, 800); }) ();Copy the code
Print the following information
You can find
Catch is the result of transferring promise state to reject state, and the previous global JS error can be caught by catch
Summary. Then. The catch
resolved
The Promise of the state will call back to the first one after it.then
rejected
The Promise of the state will call back to the first one after it.catch
- Any one
rejected
There is no state after the cut.catch
Promise can cause a global error in the Js environment
The advantages of Promise over Callback
Solve asynchronous process control problems – callback hell
Let’s continue with the interview example
Use Promise to transform the previous interview function
function interview() {
return new Promise(function (resolve, reject) {
setTimeout(() = > {
if (Math.random() > 0.4) {
// resolve, reject Accepts only one argument
resolve("success");
} else {
reject(new Error("fail")); }},1000);
});
}
(function () {
const res = interview();
res
.then((result) = > {
console.log("Great job interview! I smiled. "");
})
.catch((error) = > {
console.log("Failed the interview! I cried. ""); }); }) ();Copy the code
.then tests for throwing errors
function interview() {
return new Promise(function (resolve, reject) {
setTimeout(() = > {
if (Math.random() > 0.4) {
// resolve, reject Accepts only one argument
resolve("success");
} else {
reject(new Error("fail")); }},500);
});
}
(function () {
const promsie1 = interview();
const promsie2 = promsie1.then((result) = > {
throw new Error("Great job interview! I laughed, but I said no.");
});
setTimeout(() = > {
console.log("promsie1", promsie1);
console.log("promsie2", promsie2);
}, 800); }) ();Copy the code
As you can see from the above code,**.then
Returns a brand new Promise whose resulting state is defined by.then
To determine the result of the callback function
- If the callback function ends up being
throw
“, enter rejected - If the callback function ends up being
return
, enter Resolved
. The condition test of normal value in catch
function interview() {
return new Promise(function (resolve, reject) {
setTimeout(() = > {
if (Math.random() > 0) {
// resolve, reject Accepts only one argument
resolve("success");
} else {
reject(new Error("fail")); }},500);
});
}
(function () {
const promsie1 = interview();
const promsie2 = promsie1.catch((result) = > {
return "I failed the interview, but I smiled.";
});
setTimeout(() = > {
console.log("promsie1", promsie1);
console.log("promsie2", promsie2);
}, 800); }) ();Copy the code
.catch returns a brand new Promise, the state of which is determined by the result of the.catch callback
- If the callback function ends up being
throw
“, enter rejected - If the callback function ends up being
return
, enter Resolved
.catch,.then return Promise
function interview() {
return new Promise(function (resolve, reject) {
setTimeout(() = > {
if (Math.random() > 0.4) {
// resolve, reject Accepts only one argument
resolve("success");
} else {
reject(new Error("fail")); }},500);
});
}
(function () {
const promsie1 = interview();
const promsie2 = promsie1
.then((result) = > {
return new Promise(function (resolve, reject) {
setTimeout(() = > {
resolve("Great job interview! Give me 400ms.");
}, 400);
});
})
.catch((result) = > {
return new Promise(function (resolve, reject) {
setTimeout(() = > {
resolve("Failed interview. Give me 400ms.");
}, 400);
});
});
setTimeout(() = > {
console.log("800ms promsie1", promsie1);
console.log("800ms promsie2", promsie2);
}, 800);
setTimeout(() = > {
console.log("1000ms promsie1", promsie1);
console.log("1000ms promsie2", promsie2);
}, 1000); }) ();Copy the code
If a Promise is returned in.catch,.then, the execution result of that Promise is awaited
If the callback function eventually returns a Promise, the Promise and the Promsie state of the return of the callback function match, which means that multiple asynchronous tasks can be executed sequentially within the chained call of the Promise!
Promise implements multiple rounds of interviews – serial
What is the first round of the interview
function interview(round) {
return new Promise(function (resolve, reject) {
setTimeout(() = > {
if (Math.random() > 0.4) {
// resolve, reject Accepts only one argument
resolve("success");
} else {
const error = new Error("fail"); reject({ round, error }); }},500);
});
}
(function () {
interview(1)
.then(() = > {
return interview(2);
})
.then(() = > {
return interview(3);
})
.then(() = > {
console.log("Success in every interview! I smiled happily.");
})
.catch((err) = > {
console.log(The first `${err.round}I failed in the interview); }); }) ();Copy the code
Promise’s.then.catch turned callback hell into a linear piece of code!
Promise implements multiple company interviews – parallel
What is the first round of the interview
function interview(name) {
return new Promise(function (resolve, reject) {
setTimeout(() = > {
if (Math.random() > 0.4) {
// resolve, reject Accepts only one argument
resolve("success");
} else {
const error = new Error("fail"); reject({ name, error }); }},500);
});
}
(function () {
Promise.all([interview("tenxun"), interview("ali"), interview("baidu")])
.then(() = > {
console.log("Every company got the interview.");
})
.catch((err) = > {
console.log(` interview${err.name}Failed `); }); }) ();Copy the code
The last
This article is shallow, you are welcome to see the officer comments left your opinion!
Feel the harvest of the students welcome to like, pay attention to a wave!
The articles
- The most complete ECMAScript walkthrough
- What is the principle of qr code scanning login
- 15 front-end hd knowledge map, strongly recommended collection
- Front end developers should know Centos/Docker/Nginx/Node/Jenkins (🍡 long)
- Let me tell you about some awesome NPM packages