简体   繁体   中英

javascript callbacks not working async way

As I was trying to understand js callback I came across this problem. Here I am trying to alert aa after 2500 ms ie when value of aa is resolved but I am getting result as 1 .Why? I think aa is undefined here,but b() is in call stack .It should resolve actual value of aa . Please correct me if I am wrong.

 function a(b){ var aa = b(); setTimeout(function(){ alert(aa) },3000) } function b() { return setTimeout(function() { return 'alert this value !'; },2500) } a(b); 

You can not return a value from an async function like that. One way to get a similar behavior would be to use promises :

async function a(b){
    var aa = await b();

    setTimeout(function(){
      alert(aa)
     },3000)

)

function b() {
  return new Promise( (resolve, reject) => {
    setTimeout(function() {
      resolve( 'alert this value !' );
    },2500)

  }
}

a(b);

When you don't have async / await at your disposal, you can also use the then() callback of the promise in a() :

function a(b){
    b().then( (value) => {
       setTimeout(function(){
         alert(value)
       },3000)
    });
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM