preface

Recently oneself interview and watch classmate interview, feeling extremely! In fact, a lot of knowledge really read, but in the interview process will suddenly forget, you can not be angry. A good way to do this is with a teleprompter, which requires you to organize a short teleprompter in your own words and then use the teleprompter to expand on the topic. In the process of sorting out, I let myself understand again to deepen my impression, which is also conducive to my expression in the interview process. Presentation is so important in the interview process, wouldn’t it be a shame if you knew the answer to this question, and the interviewer felt like you still didn’t understand it? In fact, you can also improve your expression ability by practicing with your classmates or friends.

Interview questions are frequently asked

Var, let, and const

  • Different scope (with or without block-level elements)
    • Block-level scope: Declared variables are only valid within the code block scope
    • Var has no block-level scope. Let and const have block-level scope
  • Is there a temporary dead zone
    • Variables defined by let and const have temporary dead zones. Var does not.
    • For var, when it enters the scope of the var variable, storage is created for it immediately, and it is initialized with a value of undefined. When the function is loaded into the variable declaration statement, the variable is assigned a value based on the statement.
    • Let, on the other hand, is not a const. When it enters the scope of a let variable, storage is immediately created for it, but it is not initialized
  • Whether there is variable promotion
    • Variable promotion: Variables can be used before they are declared

    • Variables declared by var have variable promotion, while let and const do not

  • Can I repeat the declaration?
    • Var declarations can be repeated. Let and const declarations cannot be repeated
  • Can a variable be modified
    • Variables declared by var and let can be modified. Constants declared by const cannot be modified

The interviewer digs deep

1. What scope is var? I’ve been asked this in interviews, and you know what?

The scope of var is defined as follows: - Inside a function, var is a local variable and its scope is called function/local. - Outside a function, var is a global variable and its scope is called globalCopy the code

2. Problems related to variable promotion and function promotion

/ / 1
var a = 1;
function b(){
  var a = 2;
  console.log(a)   // What is output
}
b()

/ / 2
var a = 1; 
function a(){}console.log(a)  // What is output
/ / 3
var a = 1;
function a(){
	console.log(a);
}
a()// What is output
Copy the code
  • First of all, the first output is 2, and this is the scope problem, because if you define variable A inside of b(), all of you call variable A inside of the function first, and all of you output 2, and if you don’t define variable A inside of the function, then you access the global definition of A, and the chance of output is 1

  • The second output is 1, which hides the priority of variable promotion and function promotion, function declaration promotion > variable declaration promotion. When the JS parser encounters a function declaration, it will promote it to the top of the definition body first, followed by the var declaration. This will result in function A being overwritten by variable A, so it will print 1.

  • TypeError: A is not a function, a is overwritten by a, so when a() is called, an error will be reported because a is only a variable.

/ / 3
var a = 1;
function a(){
	console.log(a);
}
// a()
console.log(a); // Output is 1
Copy the code

Const const const const const const const const const const const const const const const

const obj = {
    name:"The sea".age: 18
}
obj.age = 20;
console.log(`name:${obj.name},age:${obj.age}`); 
// Output name: sea,age:20
Copy the code

Since objects are referential, only Pointers are held in obj, which means that const only guarantees that the pointer does not change. Modifying an object’s properties does not change the object’s pointer, so it is allowed. That is, a reference type defined by const is allowed to change no matter how long the pointer does not change.

const obj = {
    name:"The sea".age: 18
}
// obj.age = 20;
// console.log(`name:${obj.name},age:${obj.age}`);
obj={name:"The sea".age:18}
console.log(`name:${obj.name},age:${obj.age}`);
Copy the code

Even if the contents of the object do not change, it is not ok for the pointer to change

The difference between an arrow function and a normal function

  • Arrow functions are not requiredfunctionKeyword to create a function
  • Arrow functions can be omittedreturnThe keyword
  • The arrow function inherits the current contextthisKeywords are defined and fixed when they are defined
  • Arrow functionCall, apply, bindIt doesn’t affect itthisThe point to
  • Arrow functions have no prototypeprototype
  • Arrow functions don’t have their ownarguments

The interviewer digs deep

1. Call, apply and bind

  • All three can change the functionthisPoint to, bound by the first argument
  • If the first parameter of the three is zeroNull, and undefined“, the default point toWindow (in the browser)
  • callThe second argument is the argument list,applayIs an array,bindA list of arguments is also passed in (but this argument list can be passed in multiple times,applyandcallPass all parameters at once
  • bindchangethisInstead of executing immediately, a permanent change is returnedthisPointer to a function that we can call manually;apply.callIs called immediately

2. How to determine this of the arrow function

var name = 'small degree'
function b(){
    console.log(this); // window
    var name = 'white'
    c =() = >{
        console.log(this.name)  ;
    }
    c()
}
b()
Copy the code

hereArrow function CIs in theOrdinary function b, soArrow function c of thisIs pointing toThis of the ordinary function BOmega, omega, omega of ordinary functionsThis is the global (window), this needs to be executed in the browser environment, inThe execution in node is undefined

Promise’s static and instance methods

Note: Some of these companies will cover handwritten promises, so you can go to the source code implementation and handwriting. This knowledge point is very important, high frequency test point in high frequency test point, we must pay attention to ah! 1. Learn about the three states of Promise first

  • pendingTo be determined
  • fulfilled/resolvedCome true/settle/succeed
  • rejectedRejection/failure

There are only two possibilities for the state of the Promise object to change:

  • frompendingintofulfilled
  • frompendingintorejected

Note: Once these two situations occur, the state is determined and will not change.

A static method

  • 1.Promise.resolve

1. Resolve: Will change the state of the Promise object from Pending to Fulfilled.

new Promise(resolve= > {
      resolve('hello,' the sea)
  }).then(res= > {
    console.log(res)
  })
Copy the code
  • 2.Promise.reject

Reject: Changes the state of the Promise object from Pending to Rejected.

new Promise(reject= > {
    reject('hello,' the sea)
}).then(res= > {
  console.log(res)
})
Copy the code
  • 3.Promise.all
    • For example, when p1, P2, P3, and p4 are all executed, the page is displayed.

    • Note that the order of returned array results does not change. Even if P2 returns faster than P1, the order remains P1, P2, P3,p4

    • Promise.all returns an array of successes, failure data, and no further progress is made once a failure occurs

       let p1 = Promise.resolve('p1')
        let p2 = Promise.resolve('p2')
        let p3 = Promise.resolve('p3')
        let p4 = Promise.resolve('p4')
        Promise.all([p1, p2, p3, p4]).then(res= > {
            console.log('success', res); // Return an array
        }).catch(err= > {
            console.log('failure', err);
        })

Copy the code
  • 4.Promise.race

A Promise. Race ([P1, P2, p3,p4]) returns a result that is fast, regardless of whether the result itself is a success or a failure

let p1 = Promise.resolve('p1')
let p2 = Promise.resolve('p2')
let p3 = Promise.reject('p3')
let p4 = Promise.resolve('p4')
Promise.race([p1, p2, p3, p4]).then(res= > {
    console.log('success', res); // Return an array
}).catch(err= > {
    console.log('failure', err);
})
Copy the code
  • 5. Promise.allsettled // New features of ES11
    • This method returns a promise after all the given promises have fulfilled or Rejected, with an array of objects, each representing the corresponding promise result.

    • This is often used when you have multiple asynchronous tasks that don’t depend on each other to complete successfully, or when you always want to know the outcome of each promise.

const promise1 = Promise.resolve(3);
const promise2 = new Promise((resolve, reject) = > setTimeout(reject, 100.'foo'));
const promises = [promise1, promise2];

Promise.allSettled(promises).
  then((results) = > results.forEach((result) = > console.log(result.status)));
Copy the code

Instance method (prototype method)

  • 1.Promise.prototype.then

The method can take two callback functions as arguments, the second of which is optional. The first callback is called when the Promise object’s state changes to Resolved. The second callback is called when the Promise object’s state changes to Rejected.

var p1 = new Promise((resolve, reject) = > {
  resolve('success! ');
  // or
  // reject(new Error(" Error ") ));
});

p1.then(value= > {
  console.log(value); / / success!
}, reason= > {
  console.error(reason); // Error!
});
Copy the code
  • 2.Promise.prototype.catch

This method returns a Promise and only deals with rejected.

const p = new Promise((resolve, reject) = >{
    reject('Failed')
  }).catch(err= >{
      console.log(err);
  })
  
Copy the code
  • 3.Promise.prototype.finally

This method executes regardless of the success or failure of the previous promise, and by default passes the previous promise resolution as is. However, finally has limited influence on the resolution of the promise it returns. It can change the previous resolve to reject. You can also change the previous reject to another reject, but you cannot change the previous reject to resolve. The default

var p = Promise.resolve('ok')
.finally((res) = > { 
  return res })
.then(value= > {
  console.log('success', value)
}, (err) = > {
  console.log('failure', err)
});
Copy the code

A willresolveInstead ofreject


var p = Promise.resolve('ok')
.finally(() = > { 
  return Promise.reject('err') })
.then(value= > {
  console.log('success', value)
}, (err) = > {
  console.log('failure', err)
});
Copy the code

The interviewer digs deep

Then takes several parameters. What is the difference between the second parameter of then and catch?

Here, the interviewer asked “then” for several parameters, and I said 1; The interviewer then asks what is the difference between the second argument then and catch? Then I knew I was wrong, ah! So I certainly can’t answer this question.

Next for everyone to answer it!

The then method can take two callback functions as arguments. The second function is optional and does not have to be provided. Both of these functions accept as arguments a value passed from the Promise object. The then method returns an instance (not the original Promise instance)

The difference between

  • The first function of a then does not catch an exception. The second function of a then does not catch an exception.

  • Difference 2 and the proximity principle is adopted when the second parameter of THEN and catch catch exceptions. If both parameters of THEN exist, only the second parameter of THEN can be caught. If the second parameter of THEN does not exist, the catch method will catch exceptions.

Show the difference between the second argument to then and catch in code

const p = new Promise((resolve, reject) = >{
    resolve('for the')
  })
  p.then((res) = >{
    throw new Error('hello'); 
  },(err) = >{
      console.log(err,'First then catch error');
  }).catch((err1) = >{
    console.log(err1,'Catch an error');
  })
Copy the code

We can see that the second function in then cannot catch the exception thrown by the first function. Catch can catch the exception. If the catch is removed, an error will be reported



  const p = new Promise((resolve, reject) = >{
    resolve('It worked')
  })
  p.then((res) = >{
    throw new Error('hello'); 
  },(err) = >{
      console.log(err,'First then catch error');
  })
Copy the code

You can also continue using then to catch errors thrown in the previous THEN

const p = new Promise((resolve, reject) = >{
    resolve('It worked')
  })
  p.then((res) = >{
    throw new Error('hello'); 
  },(err) = >{
    console.log(err,'First then catch error');
  }).then((res) = >{},(err1) = >{
    console.log(err1,'Second then catch error');
  })
Copy the code

The proximity rule catches exceptions, which is difference 2

const p = new Promise((resolve, reject) = >{
    resolve('It worked')
  })
  p.then((res) = >{
    throw new Error('hello'); 
  },(err) = >{
    console.log(err,'First then catch error');
  }).then((res) = >{},(err1) = >{
    console.log(err1,'Second then catch error');
  }).catch((err2) = >{
    console.log(err2,'Catch an error');
  })
Copy the code

Difference between Promise and async/await

  • Promise is ES6 and async/await is ES7
  • Async /await is more elegant than promise
  • Reject status:
    • 1) Promise errors can be caught by catch.
    • 2) async/await can be used. Then try-catch can be used

Promise.all and promise. race

The difference between

  • Promise.all returns an array of successes, failure data, and no further progress is made once a failure occurs
  • A Promise. Race ([P1, P2, p3,p4]) returns a result that is fast, regardless of whether the result itself is a success or a failure

Promise.all

        let p1 = Promise.resolve('p1')
        let p2 = Promise.resolve('p2')
        let p3 = Promise.reject('p3')
        let p4 = Promise.resolve('p4')
        Promise.all([p1, p2, p3, p4]).then(res= > {
            console.log('success', res); // Return an array
        }).catch(err= > {
            console.log('failure', err);
        })

Copy the code

Promise.race

        let p1 = Promise.reject('p1')
        let p2 = Promise.resolve('p2')
        let p3 = Promise.reject('p3')
        let p4 = Promise.resolve('p4')
        Promise.race([p1, p2, p3, p4]).then(res= > {
            console.log('success', res); // Return an array
        }).catch(err= > {
            console.log('failure', err);
        })
Copy the code

Promise is combined with setTimeout to guess the output

console.log('start')
setTimeout(() = > {
  console.log('time')})Promise.resolve().then(() = > {
  console.log('resolve')})console.log('end')
Copy the code

Analysis of the

  • The entire script is initially executed as a macro task, and the synchronized code is pushed directly onto the stack for execution, so start and end are printed first.
  • SetTimout is put into the macro task queue as a macro task (next)
  • Promise.then is put into the microtask queue as a microtask
  • When the macro task is complete, check the microtask, find promise.then, and execute it
  • Next, the next macro task, setTimeout, is found and executed.

【 suggest stars 】 To come to 45 Promise interview questions a cool end (1.1W words carefully arranged)

conclusion

I am still a junior student. Due to limited time and energy, I will update it here temporarily. The next chapter will be sorted out as soon as possible. Now I am also constantly breaking through their own, especially the ability to express, I hope we can make progress together! If you have any questions, please point them out in the comments section. Thank you in advance! Can also ➕ wechat zxl814405253 to discuss the problem!