简体   繁体   中英

Javascript : Will a function call all callbacks for all functions that ever called it?

Say we have a function.

function kevin(cb){
   //Ok  then, so async stuff here, then, when done, 
   cb(1); <== reply;
}

Then :

....
kevin(x=> console.log(x));

Then another block calls kevin() before the above call receives a reply.

kevin(y=> console.log(y));

I'm a bit confused after working with Java for a while, with the above, in java, if these callbacks were Java Interfaces, and the second call to kevin happened before the first call was returned, the second call would override the first, and only the second would be returned, requiring the composite pattern to make sure that all callbacks are recorded and fulfilled when the method is done.

But in Javascript, I'm not getting any errors, everything works and all function callbacks that call kevin() are being called.

I'm doing this in Angular with typescript. So the above are actually methods in classes.

Subsequent function calls will not in any way replace previous function calls. If some asynchronous event is awaited inside a function, then a new callback is scheduled on the event loop for each await. Simple example:

 setTimeout(() => console.log(1)); setTimeout(() => console.log(2)); setTimeout(() => console.log(3)); 

All three callbacks will fire with their respective values.

The only time you will get interference is if you have shared variables:

 let foo = 'bar'; setTimeout(() => console.log(foo)); setTimeout(() => foo = 'baz', 500); setTimeout(() => console.log(foo), 1000); 

The result of the last callback may or may not be what you expect, if you're unaware that the shared foo is being manipulated in another callback.

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