Article From:https://segmentfault.com/q/1010000011707211
Question:

Title Description:
Modifiable function AA;

function aa () {
    setTimeout(  function(){ 
        return     "wwwwwwww";
    }  ,1000);
}

Execute the following statement
console.log(aa());

The expected goal is: console.log output “wwwwwwww” after one second.

Another requirement:
1 、aa The function can be modified at will, but there is no console.log inside.
2 、The following statement console.log cannot be wrapped by setTimeout.

This topic is leaned by the project group boss, asking for doubts!

Answer 0:
function aa() {
    let t = Date.now()
    while (Date.now() - t < 1000) {}
    return 'wwwwwwww'
}

Answer 1:

The main purpose of this problem is to examine the handling of the execution result of an asynchronous call, since it is an asynchronous call, thenIt is impossible to synchronously wait for the asynchronous result, and the result must be asynchronous.

setTimeout() It is often used to simulate asynchronous operations. At first, asynchronism is to notify the caller of processing results by callbacks.

function aa(callback) {
    setTimeout(function() {
        if (typeof callback === "function") {
            callback("wwwwwwww");
        }
    }, 1000);
}

aa(function(v) {
    console.log(v);
});

However, callbacks are prone to multiple layers of nesting when used in slightly larger asynchronous applications, so some “flat” callbacks are proposed, which can be referred to as “flat” callbacks for gossip. Of course, Promise is a popular method and is eventually adopted by ES6.. Promise is implemented as follows:

function aa() {
    return new Promise(resolve => {
        setTimeout(function() {
            resolve("wwwwwwww");
        }, 1000);
    });
}

aa().then(v => console.log(v));

In this case, it is much the same as the preceding callback. However, it will lead to a more recommended method, async/await, from ES2017.

function aa() {
    return new Promise(resolve => {
        setTimeout(function() {
            resolve("wwwwwwww");
        }, 1000);
    });
}

async function main() {
    const v = await aa();
    console.log(v);
}

main();

aa() The definition is the same as the definition in the Promise method, but it is used when it is called.await,Waiting asynchronously, waiting for the result of asynchronism, then use it againconsole.log() Deal with it.

What we need to pay attention to here isawait Only inasync Used in the method, so in order to useawait One must be defined.async The main method is invoked in the global scope. Because the main method is asynchronous (declared async), so ifmain() After the call, there are other statements, such asconsole.log("hello"),Then this sentence will be executed first.

async/await Syntax makes asynchronous calls write like synchronous code, avoiding logical jumps and making it easier to write when writing code. (Reference: from hell to heaven, Node callback to async/await)

Of course, definition.main() Call againmain() This part can be encapsulated by IIFE.

(async () => {
    const v = await aa();
    console.log(v);
})();

Answer 2:

Using promise

function aa () {
    return new Promise(function(resolve,reject){
        setTimeout(  function(){ 
           resolve("wwwwwwww");
        }  ,1000);
    })
 }
 
aa().then(function(a){
    console.log(a);
});

Answer 3:
function aa () {
    setTimeout(  function(){ 
        return     "wwwwwwww";
    }  ,1000);
    return "wwwwwwww"
}

A slant smile

Answer 4:
function aa(callback){
    setTimeout(function(){
        callback();
    }, 1000);
}

aa(function(){
    console.log('wwww');
});

Answer 5:

Although the final answer is right, the new Date upstairs is right.
But actually this question really wants to assess is asynchronous operation, think of ES6’s Promise.
The code is as follows:

function aa(){
  return new Promise((resolve) =>{
    setTimeout(()=>{
      resolve("wwwww")
    }, 1000)
  })
}

aa().then((result)=>{
  console.log(result)
})

Answer 6:

Let’s talk about a local way.

function aa () {
var a = Date.now();
do{
var current = Date.now();
}while(current-a<1000);
return 'www';
}

Answer 7:

function aa(){

return new Promise(function(resolve){
    setTimeout(function(){
        resolve('wwwwwwwww')
    },1000);
});

}
aa.then(function(a){

console.log(a);

});

Similar Posts:

Link of this Article: A small topic with connotations.

Leave a Reply

Your email address will not be published. Required fields are marked *