The preparatory work
Instance objects and function objects
function Fn(){ } const fn=new Fn(); //fn is the instance object, console.log(fn. Prototype); //Fn is a function object, using a function as an objectCopy the code
Whatever you write to the left of the parentheses must be a function, so if you write a(), then we know that A must be a function. To the left of the point, it has to be an object.
When you look at code, you need to know the data types, first understand the syntax, then understand the functionality.
The two types of callback functions are synchronous and asynchronous callbacks
What function is a callback function? Three conditions must be met at the same time:
- The callback function should be defined by you
- I didn’t call the callback myself
- But he did
// const arr=[1,3,5]; Arr.foreach (item=>{// this is the synchronous callback function. It will not be queued until it is finished. // He prints first}); The console. The log (' forEach () '); SetTimeout (()=>{// This is the asynchronous callback function that will be queued for future execution console.log('aaa'); // After he prints},0); console.log('bbb'); // He prints firstCopy the code
Error handling in JS
Common built-in errors
- ReferenceError The referenced variable does not exist
- TypeError An error with an incorrect data type
- The RangeError data value is not in the range it allows
- SyntaxError SyntaxError
The error is not caught, and the following code does not execute
Error handling (catch and throw)
Capture with try… catch
try{ let d; console.log(d.xxx); } catch (error){// Here's a debugging trick. If you don't know what properties are in the error, you can put a breakpoint on this line and then hover it over the source to see console.log(error.message); } console.log(' after error '); // This is the line where the output is because the error is handledCopy the code
You throw an error by yourself
function something(){
if(Date.now()%2===1){
console.log('111');
} else { //如果时间是偶数,抛出异常,由调用者来处理
throw new Error('222');
}
}
try {
something();
} catch (error) {
console.log(error.message);
}
Copy the code
Understanding and using promise
The basic process of learning technology, getting a new thing, what is that thing? Why do we use this? How do I use this? The first two should not be forgotten, but the grammar can be forgotten
What is the promise
Promise to give you a data in the future, but the success of the data or the failure of the data I do not know at first
Abstract: this is a new solution for implementing asynchronous programming in JS. The old one was in the form of pure callbacks. Why say pure
More specifically: A Promise is a constructor, and a Promise object is used to encapsulate an asynchronous operation and retrieve its results
Promise’s status changed
- Pending to resolved
- Pending a rejected
There are only two changes, and a Promise object can only change once, with a result data whether it becomes a success or a failure
Promise’s basic process
Create a new promise object, new Promise(), this promise object is in the pending state, this promise object is in the pending state, this promise object is in the pending state, this promise object is in the pending state, this promise object is in the pending state, this promise object is in the pending state. The Promise object becomes in the Resolved state. Once it is in the resolved state, the successful callbacks are called. Then () can specify the successful and failed callbacks. When an asynchronous task fails, reject() is executed. The Promise object changes to the rejected state and then calls the failed callback function. Catch () specifies the failed callback function. Both then() and catch() return new Promise objects.
Promise’s basic use
What do you mean by “return a promise”
Const p=new Promise((resolve,reject)=>{setTimeout(()=>{const time= date.now (); if(time%2==0){ resolve('succcess'); } else{ reject('fail'); }}, 1000)}); P.t hen (/ / success callback function value = > {/ / a value is not to take on my own, but he himself to me, the same to the following reason}, / / callback function failure reason = > {})Copy the code
Why use a promise
Suppose you have a function called createAudioFileAsync() that receives some configuration and two callback functions, and then asynchronously generates an audio file. One callback is called when the file is successfully created, and the other is called when an exception occurs.
Function successCallback(result) {console.log(" audio file created successfully: "+ result); } function failureCallback(error) {console.log(" failed to create audio file: "+ error); } // In the past, you must specify the success and failure callbacks before you actually perform an asynchronous operation. CreateAudioFileAsync (audioSettings, successCallback, failureCallback) Const Promise = createAudioFileAsync(audioSettings); promise.then(successCallback, failureCallback); // If your asynchronous task takes 2 seconds to execute and I give you the then callback after 3 seconds, I can still execute the callback normally. // If I give you the then callback after 3 seconds, I can execute the callback normallyCopy the code
That said, the first advantage of a Promise over traditional pure callbacks is that it is more flexible to specify the callback function. Promise: Start an asynchronous task = “return a Promise object =” and specify the callback function to the promise object
The second advantage is that promise supports chained calls, which can solve the callback hell problem. The ultimate solution to callback hell is async and await, which have no callback functions
// If the first asynchronous task depends on the result of the first asynchronous task, then the second asynchronous task depends on the result of the first asynchronous task. DoSomething (function(result) {doSomethingElse(result, function(newResult) {doThirdThing(newResult, function(finalResult) { console.log('Got the final result: ' + finalResult); }, failureCallback); }, failureCallback); }, failureCallback); Dosomething.then (function(result) {return doSomethingElse(result); }).then(function(newResult) {return doThirdThing(newResult); }) .then(function(finalResult) { console.log('Got the final result: ' + finalResult); }) .catch(failureCallback); // If any of the above three exceptions, will jump here, the exception is transmitted throughCopy the code
async function foo() { try { const result = await doSomething(); const newResult = await doSomethingElse(result); const finalResult = await doThirdThing(newResult); console.log(`Got the final result: ${finalResult}`); } catch(error) { failureCallback(error); }}Copy the code
How to Use promises
Do not have obstacles in grammar, feel do not understand their own way
The API looks at the MDN itself
The promise.prototype.then () method returns a new Promise object
New Promise((resolve,reject)=>{// you don't have to call either of these names, use any}) // Create a Promise object with a success or failure value, Const p1=new Promise((resolve,reject)=>{resolve(1); }) const p2= promise.resolve (2); const p2= promise.resolve (2); const p3=Promise.reject(3); p1.then(value=>{console.log(value)}); p2.then(value=>{console.log(value)}); p3.catch(reason=>{console.log(reason)}); const pAll=Promise.all([p1,p2,p3]); pAll.then( values=>{}, reason=>{ console.log(reason); //3 } ) const pRace=Promise.race([p1,p2,p3]);Copy the code
Promise’s key questions
1. How to change the state of a promise? In addition to resolve(value) and Reject (Reason), you can throw an exception, or if it is pendding, it will become Rejected
const p=new Promise((resolve,reject)=>{ throw new Error('aaa'); // The reason is the error that was thrown // You can throw a 3 directly //throw 3; "Reason for 3})Copy the code
2. If a promise specifies multiple success/failure callbacks, will they be called?
Yes.
//promise (value=>{... }, reason=>{... } ) p.then( value=>{... }, reason=>{... })Copy the code
3. Which comes first, changing the promise state or specifying the callback function?
Either way, you can specify the callback first or change the promise state first.
new Promise((rosolve,reject)=>{ setTimeout(()=>{ resolve(1); // How does he know where the callback function is? },1000)}).then(value=>{}, reason=>{console.log(reason)}). Then () New Promise((rosolve,reject)=>{resolve(1); }).then().then().then().then().then().then().then().then().then().then Value =>{}, reason=>{console.log(reason)})Copy the code
4. What determines the result status of the new promise returned by promise.then()?
(Incidentally, then concatenates multiple operation tasks, which is one of its uses.)
Simply put: it is determined by the result of the execution of the callback function specified by then()
(1) If you throw an exception, the new promise becomes rejected, and the reason is the exception you rejected. If you throw an Error object, the reason is the exception you rejected. If you throw an Error object, the reason is the exception you rejected
(2) If any value is returned that is not a PROMISE, the new promise becomes resolved and the value is the returned value (for example, if you write synchronous operations in then).
(3) If a new promise is returned, the result of that promise will be the result of the new promise (for example, if you write an asynchronous operation in then).
new Promise((resolve,reject)=>{
resolve(1)
}).then(
value=>{
console.log(value);
//return 2;
//return Promise.resolve(3);
//return Promise.reject(4);
//throw 5;
},
reason=>{
console.log(reason);
}
).then(
value=>{console.log(value)},
reason=>{console.log(reason)}
)
Copy the code
5. Chain calls, each chain only to see what is returned by the link in front of him, do not look beyond the level; Also, you should not confuse the then/catch function itself with the one specified in the “then”/” catch “function. This does not mean that a catch returns a promise. It depends on what the function returns
6. Promise exception transmission
Exception pass-through is not skipped in one step, but also passed level by level
new Promise((resolve,reject)=>{ reject(1) }).then( value=>{ console.log(value); }, // reason=>{throw reason}.then(value=>{console.log(value); Reason =>{console.log(reason); })Copy the code
How to break the promise chain?
new Promise((resolve,reject)=>{ reject(1) }).then( value=>{ console.log(value); } ).catch( reason=>{ console.log(reason); Return new Promise(()=>{}) // Return Promise(()=>{})).then(// this callback will not be called value=>{console.log(value); })Copy the code
Write a Promise
See the code
Async and await
// The result of this Promise object is determined by the return value of async function fn1(){//return 1; //throw 2; return Promise.resolve(3); } const result=fn1(); result.then( value=>{ console.log('onResolved()',value); }, reason=>{ console.log('onRejected()',reason); } ) function fn2(){ return new Promise((resolve,reject)=>{ setTimeout(()=>{ resolve(5); },1000)})} async function fn3(){//await function must be declared as async, but async function can have no await in it. Catch to handle const value=await fn2(); //const value=await 3; // await 3; }catch(error){console.log(' failed to obtain result ',error); } } fn3();Copy the code
Macro queues and micro queues
Macro queue: DOM event callback, Ajax callback, timer callback
Microqueue: Promise callback, mutation callback
After all the synchronized code has been executed, the callback function in the queue will be executed. Each time the first macro task is ready to be fetched, all microtasks will be fetched and executed one by one.