Promise is an old friend of all of us, and we can’t live without it, whether it’s interview or daily development. Promise interview questions, but the Angle of the proposition can not escape the following three lines:

  • Examine the Promise feature (QUESTION and answer)
  • Give a piece of Promise code and ask for the output.
  • Delve deeper into the Promise principle (the ultimate version lets you write a Promise by hand)

By knowing how to answer all three of these questions, you’ve turned Promise upside down. You’ll be able to follow through on even more tricky Promise questions in the future.

Proposition 1: Promise feature class problem

The Promise feature quiz is designed to test your familiarity with the Promise basics. What you need to pay attention to are the “three questions of the soul” :

an

Q: Tell me about the Promise you understand

The proxy object, the three states, and the state switching mechanism

A small example: The Promise object is a proxy object. It takes the executor you pass in as an input parameter, allowing you to bind the success and failure of an asynchronous task to the corresponding handler. A Promise instance has three states: • Pending state, which indicates ongoing. This is an initial state after the Promise instance is created; • A state of pity, which means to complete successfully. This is the state reached when we call resolve in the executor; • Rejected state: Indicates that the operation fails or is rejected. This is the state we reach when we call reject in the actuator; The state of a Promise instance can change, but it is only allowed to change once. When our instance state changes from Pending to Rejected, it cannot be reversed to depressing again, and vice versa. When the state of Promise is resolved, the corresponding THEN method will be triggered to enter the ondepressing function in the parameter. When the Promise status is Rejected, the onRejected function in the corresponding catch method is triggered.

Question 2

Q: What problem was Promise created to solve?

Small examples: Improve execution efficiency, gracefully solve asynchronous problems, avoid callback hell, and make your code more readable and maintainable.

Question 3

Q: What are some common approaches to Promise? What do you do?

Answer all, Race, reject and resolve.

Here’s a quick example: Promise can be used in the following ways:

  • Promise. All (iterable) : This method returns a new Promise object that will succeed only if all the promise objects in the Iterable argument object succeed. The failure of any of the iterable promise objects triggers the failure of that promise object. Here’s an example:
var p1 = Promise.resolve('Player Number one');
var p2 = 'Player Number two';
var p3 = new Promise((resolve, reject) = > {
  setTimeout(resolve, 100."Player Number three.");
}); 
Promise.all([p1, p2, p3]).then(values= > { 
  console.log(values); // [" No.1 Contestant ", "no.2 contestant "," no.3 contestant "]
});
Copy the code
  • Promise. Race (iterable) : When any child promise in the iterable argument succeeds or fails, the parent promise immediately calls the parent promise’s binding handler using the child promise’s success return value or failure details as arguments and returns the promise object. Here’s an example:
var p1 = new Promise(function(resolve, reject) { 
    setTimeout(resolve, 100."Player Number one"); 
});
var p2 = new Promise(function(resolve, reject) { 
    setTimeout(resolve, 50."Player Number two"); 
});

// Player 2 returns earlier, so the return value is player 2
Promise.race([p1, p2]).then(function(value) {
  console.log(value); // "Player no. 2"
});
Copy the code
  • Promise.reject(reason) : Returns a Promise object in a failed state and passes the given failure information to the corresponding handler
  • Promise.resolve(value)It returns a Promise object, but the state of the object depends on the value you pass in, in one of two ways:
    • If an object is passed in with a THEN method (we call it a Thenable object), the final state of the returned Promise object is determined by the then method execution
    • Otherwise, the Promise object will be returned with the state of fulfilled, and the value will be used as an entry to the onfulfilled specified in the THEN method

Proposition point 2: look at the code to say the answer type of question

Just because you can say what a Promise is, doesn’t mean you understand it and can actually do something with it. The interviewer will often show you the code to see how much you weigh. Let’s go through three good questions and look at the proposition rules of these code class questions.

an

const promise = new Promise((resolve, reject) = > {
    console.log(1);
    resolve();
    console.log(2);
});

promise.then(() = > {
    console.log(3);
});
console.log(4);
Copy the code

Running results:

The handler in Promise is an asynchronous task

Analysis: The task passed in the THEN method is an asynchronous task. Resolve () is a call that sets the Promise’s state from pending to depressing. This new state will let the Promise know that “that task in my then method can be fulfilled” — this is a big pity. Instead of saying, “It will be implemented immediately.” After all, as an asynchronous task, the essence of it is to wait until the synchronous code has finished executing. So the output of the number 3 comes last.

Question 2

const promise = new Promise((resolve, reject) = > {
  resolve('1st resolve')
  console.log('Normal logic after Resolve')
  reject('error')
  resolve('resolve 2nd time')
})
 
promise
.then((res) = > {
  console.log('then: ', res)
})
.catch((err) = > {
  console.log('catch: ', err)
})
Copy the code

Running results:

The state of a Promise object can only be changed once

This is a pity state. The promise state is “pending”. This is a pity state. After this switch is completed, all subsequent attempts for state switch are not effective, so the subsequent reject and resolve are ignored directly. Note that we ignore reject, resolve after the first resolve, not all code behind it. So console.log(‘ normal resolve ‘) can still be executed. It is the same reason why it is printed in front of “then: 1st resolve”

Question 3

Promise.resolve(1)
  .then(Promise.resolve(2))
  .then(3)
  .then()
  .then(console.log) // .then(a => console.log(a))
Copy the code

Running results:

1
Copy the code

1. The Promise penetrates the question

Analysis:.then or.catch parameters are expected to be functions, and value penetration occurs when passing non-functions; The chain of Promise methods passes values through returns, without which they are just separate tasks. Because promise.resolve (‘bar’) is a static method that calls a Promise directly, the result is a Promise object, which is the core point at which the Promise resolves the callback hell to get the callback under control.

Here are two more examples of code:

/ / value through
Promise.resolve(1)
  .then(() = > {return 2})
  .then(Promise.resolve(3))
  .then(console.log); / / 2

// pass the values in sequence
Promise.resolve(1)
  .then(() = > {return 2})
  .then(() = > {return Promise.resolve(3)})
  .then(console.log); / / 3
Copy the code

Thesis point 3: Investigate the underlying principle of Promise

When it comes to the underlying principles of promises, some interviewers will ask you to describe how A Promise/A+ plan will work. More interviewers will ask you to write A simple Promise by hand — talk is cheap, after all.

But this kind of problem is easy to solve, and since handwritten promises are the ultimate form, let’s solve the ultimate form. In the process of writing a Promise, the underlying principles, including implementation details, will be absorbed, and you won’t have to worry about it later, even if it comes in the form of an essay question. See you later in the article “Promise/A+” for specific handwritten promises