Really understand promise and synchronous and asynchronous new interview techniques

Promise, which is a big problem, belongs to the truth. I understand it and can use it, but I always feel that I don’t understand it thoroughly. I
found a video on Bilibili, which solved my years of doubts.

Bilibili link

Synchronous: Submit the request -> wait for the server to process -> the client browser can't do anything during this period.
Asynchronous: the request is triggered by an event -> server processing (this is the browser can still do other things) -> processing is completed

simulation one

function one (){
    
    
     return 'I am one';
}
function two () {
    
    
     setTimeout(()=>{
    
    
           return 'I am two';
     },3000);
     
}
function three () {
    
    
     return 'I am three';
}

console.log(one())
console.log(two())
console.log(three())

insert image description here

  • Background data requests are all asynchronous, while JS is single-threaded. Here, the timing function is used to simulate the request, and it will be found that the output will be executed before the request is completed, resulting in the output of undefined

simulation two


function one (){
    
    
     return 'I am one';
}
function two () {
    
    
     return new Promise((resolve,reject)=>{
    
    
          setTimeout(()=>{
    
    
                resolve ('I am two');
          },3000);
     })
}
function three () {
    
    
     return 'I am three';
}

console.log(one())
console.log(two())
console.log(three())

insert image description here
Here, because it is still executed directly by a single thread, the promise object is output without waiting for the promise success state, and the promise object is in the pending state at this time.

simulation three


function one (){
    
    
     return 'I am one';
}
function two () {
    
    
     return new Promise((resolve,reject)=>{
    
    
          setTimeout(()=>{
    
    
                resolve ('I am two');
          },3000);
     })
}
function three () {
    
    
     return 'I am three';
}

console.log(one())
console.log(await two())
console.log(three())

insert image description here
With await, when the code is executed, await returns a result before continuing to execute downwards.
Here it will output first I am oneand then wait for three seconds before outputtingI am two I am three

  • The initial solution is to use the callback function method to pass in subsequent operations, so that other logic can be executed after getting the data.
  • But too many callbacks will lead to callback hell, which is difficult to maintain. The main contribution of promise is to solve the callback hell and make the request code more concise. After adding async, it will be more comfortable to write.

a noteworthy point

I remembered that in the previous interview, an interviewer asked me why I had to handwrite the promise object when I used promise. The await returned was the promise object. I didn't think about it at the time. Looking back now...Fortunately, I didn't go
to the description of await in that company's MDN

If the value is not a Promise, await converts the value to a normally resolved Promise, and then waits for its result.

async function f2() {
    
    
  var y = await 20;
  console.log(y); 
}f2();
//输出20

What await returns is the promise object. This sentence is actually correct, but let’s take a look at it in combination with actual development.
Use timers to simulate asynchronous requests. The scenario is that you need to get the result returned by the interface before proceeding to the next step.

async function f2() {
    
    
  var y = await two();
  console.log(y); // 20
  console.log('下一步')
}
function two () {
    
    
     setTimeout(()=>{
    
    
           return 'I am two';
     },3000);
}
f2()
//输出 undefined
//     下一步 

The result returned in this way is undefined. If the asynchronous request is not manually encapsulated and is automatically processed by await, the blocking effect of await will not appear, and the data will still not be available.
The correct way to write is:

async function f2() {
    
    
  var y = await two();
  console.log(y); // 20
  console.log('下一步')
}
function two () {
    
    
    return new Promise(resolve=>{
    
    
         setTimeout(()=>{
    
    
               resolve( 'I am two')
         },3000);
    })
}
f2()
//等待三秒后
//输出 I am two
//     下一步 

Interview speech:

JS is single threaded, but background requests are executed asynchronously. In development, it is often encountered that the necessary logic needs to be executed after obtaining the interface data.
Of course, a callback function can be used here, but if the amount of code is too large, it will be difficult to maintain and form a callback hell.
Using the promise function with async await can perfectly solve this kind of problem. In
a certain step, set await to wait for the returned promise object, and make an asynchronous request in the promise.
Use synchronous method to write asynchronous, high maintainability.

Guess you like

Origin blog.csdn.net/Beatingworldline/article/details/120831089