catalogue
Promise summarized it by himself
4,promise State change understanding promise
9. The promise key throws an error message
10. Who is the first to change promise status and execute callback? The following code.
11. What determines the result status of the new promise returned by promise.then()?
13. promise abnormal transmission / pierce through?
14. async function and await function
16. promise interview questions promise classic interview questions
The next chapter contains handwritten Promise encapsulation Promise
Promise summarized it by himself
1, Error type
Error : Parent type of all errors
ReferenceError: error with incorrect reference type
TypeError: error with incorrect data type
RangeError: the data value is not within its allowed range
Syntax error: syntax error
2, error handling
Capture error: try ... catch
Throw error throw error
Catch exception error handling
var num = 5 function fn() { if (2 > num) { console.log('Can perform tasks'); } else { throw new Error('Wrong information') } } try { // Throw out error message fn() } catch (error) { console.log(error); }
3, Error object
Message attribute: error message related // stack The error report has information and type combination
Stack attribute: function call stack record information It is the stack memory overflow error. Call yourself
SyntaxError capture Syntax error var a = """ Uncaught SyntaxError: Invalid or unexpected token
4,promise State change understanding promise
promise Is an asynchronous programming solution proposed by es6
pending becomes resolved
pending become rejected
resolve is used to convert promise from an ongoing state to a successful state
reject The function of promise is to convert promise from an ongoing state to a failed state
promise Is essentially a constructor It has three states namely pending Succeeded (fullfilled) Failed (rejected)
Note: there are only two and one promise The object can only be changed once
Whether you succeed or fail, there is only one result The result of success is generally called value The result of failure becomes reason
promise can be converted from an in progress state to a successful state You can also from the in progress state Convert to failed state
promise Whether it's success or failure It's all over therefore Promise cannot transition from a successful state to a failed state
Nor can it transition from a failed state to a successful state
The promise constructor accepts a function as an argument The function internally accepts two parameters They are resolve reject
5,promise Use of
const p = new Promise((resolve, reject) => { // new Promise passes in a callback function. The fixed parameter name is resolve reject console.log(1); // The synchronized code is executed first setTimeout(() => { console.log(3); // Asynchronous post execution if (5 > 2) { resolve('Successful callback') } else { reject('Failed callback') } }, 1000); }) console.log(2);// The synchronized code is executed first p.then( value => { console.log(value);// The successful data above the value here is resolve }, reason => { console.log(reason);// The successful data on reason here is reject } )
7. Why Promise
1. Specifying callback functions is more flexible
Old: the instruction must be before starting an asynchronous task
Promise : Start asynchronous task => Return promise object => Give promise Object binding callback function (can even be specified after the asynchronous task ends)
2. Support chain call, which can solve the callback problem Question of
What is hell ? Callback functions are nested and called layer by layer. The result of asynchronous execution of external callback functions is the condition for the execution of nested callback functions
Disadvantages of callback hell? It's not easy to read / Not convenient for exception handling
Solution? promise call chaining first-class async / await
8,Promise Syntax api
const p = new Promise((resolve, reject) => { setTimeout(() => { // There can only be one state here resolve('success') reject('fail') }, 0); }) p.then( value => { console.log(value);// The successful data above the value here is resolve }, reason => { console.log(reason);// The successful data on reason here is reject } ) // Abbreviation const p = new Promise((resolve, reject) => { resolve('success') }) //This can be abbreviated as the following p.then( value => { console.log(value);// The successful data above the value here is resolve }, reason => { console.log(reason);// The successful data on reason here is reject } ) //This can be abbreviated as the following const p = Promise.resolve('Success 11') //Abbreviated formal grammar const p1 = Promise.resolve('Succeeded 22') const p2 = Promise.reject('Failed 333') p.then((resolve) => { console.log(resolve) }) p1.then((resolve) => { console.log(resolve) }) p2.catch((reject) => { console.log(reject) }) // Promise.all Promise.all You can combine the results of multiple callbacks const pAll = Promise.all([p, p1, p2]) pAll.then( value => { console.log('on Resolve', value); }, reason => { console.log('on Reject', reason); } ) // Promise.race Promise.race The first result is the final result const pAll = Promise.race([p2, p, p1,]) // Here, if p2 is placed in the first execution, it is a failure, and the last one is a success pAll.then( value => { console.log('on Resolve', value); }, reason => { console.log('on Reject' + reason); } )
9. The promise key throws an error message
const p = new Promise((resolve, reject) => { throw new Error('There is an error message, please handle it') //1. How to change the promise state? resolve, reject, or throw an error message or exception. Promise becomes the reject state }) p.then( value => { }, reason => { console.log('1---' + reason);// This is an error message } ) p.then( value => { }, reason => { console.log('2---' + reason);// This is an error message } ) //2. Does a promise specify multiple callback functions to call back? When a promise changes, the corresponding state will change and print all
10. Who is the first to change promise status and execute callback? The following code.
1. When do you get the data
2. If the callback is specified first, when the state is released and changed, the callback function will be called to get the data
3. If the state of the is changed first, the callback function will be called when it is specified
new Promise((resolve, reject) => { setTimeout(() => { reject(1)//2. After changing the state (specifying data at the same time), the callback function is executed asynchronously }, 1000); }).then(//1. Specify the callback function first and save the currently specified callback function value => { }, reason => { console.log('fail' + reason);// This is an error message } ) new Promise((resolve, reject) => { reject(1)//1. First change the state (specify data at the same time) and execute the callback function asynchronously }).then(//2. After specifying the callback function, execute the callback function asynchronously value => { }, reason => { console.log('fail' + reason);// This is an error message } ) 2,Synchronous and asynchronous code new Promise((resolve, reject) => { reject(1) }).then( // . then whether it succeeds or fails, it is asynchronous. / / synchronous execution first and asynchronous execution later value => { }, reason => { console.log('fail' + reason); } ) console.log(2); // console.log(2) is executed first. console.log('failure '+ reason) is asynchronous in output.
11. What determines the result status of the new promise returned by promise.then()?
1. Simple expression: determined by the execution result of the callback function specified by then()
2. Detailed expression:
If an exception is thrown, the new promise Become rejected reason is the exception thrown
If any value other than promise is returned, the new promise becomes resolved , value Value returned for
If another new promise is returned, the result of this promise will become the result of the new promise
new Promise((resolve, reject) => { resolve(1) // reject(1) }).then( // then is determined by the result of promise value => { console.log(value); //If no exception is thrown here, it is equivalent to an undefined return // return 2 if a 2 is returned here, then the value in. Then is 2, not undefined // return Promise.resolve(2) / / the value in. then below is 2 // return Promise.reject(2) / / next, execute the failed callback. Reason in then / / 2 // Throw 'throw an exception' / / an exception is thrown here }, reason => { console.log('fail' + reason); } ).then(// Determined by the function executed above value => { console.log(value); // undefined }, reason => { console.log('fail---' + reason); } )
12,promise How to concatenate multiple asynchronous operation tasks then of promise returns a new promise, which can open the chain call
1. Multiple synchronous and asynchronous tasks can be concatenated through then chained calls
new Promise(resolve => { setTimeout(() => { resolve(1) }, 1000); }).then(value => { console.log(value); return 2 }).then(value => { console.log(value); return new Promise(resolve => { setTimeout(() => { resolve(3) }, 1000); }) }).then(value => { console.log(value); })
13. promise abnormal transmission / pierce through?
When using promise's then call, you can specify the failed callback at the end
When any previous operation has an exception, it will be transferred to the last failed callback for processing
Return new promise (() = > {}) / / there is no result here and no result below pending interrupt promise chain
new Promise(resolve => { resolve(1) }).then(value => { console.log(value); return 2 // reason => { throw reason } }).then(value => { console.log(value); return 3 // reason => { throw reason } }).then(value => { console.log(value); // reason => { throw reason } // 7. Return new promise (() = > {}) / / there is no result here, and there is no result below. pending interrupts the promise chain }).catch((reason) => { // Transparent errors are passed layer by layer. How can promise fail 1. Throw an exception 2. reject console.log(reason); })
14. async function and await function
be careful:
Await must be written in async function, but there can be no await in async function
If the promise of await fails, an exception will be thrown, which needs to be captured and processed through try...catch
async Function is a solution to asynchronous programming It is encapsulated by promise
await It can obtain the result of promise execution Await must be used with async
The asynchronous operations we usually involve are setInterval setTimeout ajax request Various events, etc
1,async function
async function The return value of is a promise object
promise The result of the object is determined by the return value of the async function
async function fn() { // The return value of the async function is a promise object return } let a = fn() console.log(a);
2,await expression
await The expression on the right is generally promise object But it can also be other values
If Expressions are promise objects, await Returns the value of promise success
If the expression is another value, Take this value directly as the return value of await
function fn() { return new Promise((resolve, reject) => { setTimeout(() => { // resolve(123) // a reject('error') // 1 }, 1000); }) } async function fn1() { // If await is used in this function, async must be used // let fun = await fn() // b try {// This is the 2 that caught the error let fun = await fn() } catch (error) { console.log(error); } // console.log(fun);// c // If the expression is a promise object, await returns the value of promise success } fn1() function fn() { return 6666 } async function fn1() { // If await is used in this function, async must be used let fun = await fn() // If the expression is another value, this value is directly used as the return value of await console.log(fun); } fn1()
15. Macro queue , Microqueue
Macro queue dom event callback ajax callback Timer callback
Microqueue Promise callback mutation callback
js execution distinguishes the two queues
The js engine must first execute all initialization synchronization code The macro queue is being executed after the micro queue is executed
Every time you are ready to take out the first macro task for execution, take out all micro tasks one by one
Here's the code
setTimeout(() => { // Join macro queue console.log(1); }); Promise.resolve(3).then((value) => { // Join micro queue console.log(value); }) setTimeout(() => { console.log(5); Promise.resolve(6).then((value) => { // Join micro queue console.log(value); }) }); Promise.resolve(2).then((value) => { // Join micro queue console.log(value); setTimeout(() => { // Join macro queue console.log(4); }); }) // 3 2 1 5 6 4 setTimeout(() => { console.log(1); }); new Promise((resolve) => { console.log(2); resolve() }).then(() => { console.log(3); }).then(value => { console.log(4); }) console.log(5); // Every time you are ready to take out the first macro task for execution, take out all micro tasks one by one // Micro queue [2 5 3 4] macro queue [1] 25341
16. promise interview questions promise classic interview questions
setTimeout(() => { console.log(0); }, 0); new Promise((resolve, reject) => { console.log(1); resolve() }).then(() => { console.log(2); new Promise((resolve, reject) => { console.log(3); resolve() }).then(() => { console.log(4); }).then(() => { console.log(5); }) }).then(() => { console.log(6); }) new Promise((resolve, reject) => { console.log(7); resolve() }).then(() => { console.log(8); }) // 1 7 2 3 8 4 6 5 0