-
-
Save vasanthk/dc4cb612b089085d7b74 to your computer and use it in GitHub Desktop.
| var cbFn = function() { | |
| console.log('Done') | |
| } | |
| // Run Async API call | |
| completeAsyncCheckout(data, cbFn); | |
| cbFn = function() { | |
| // Guessing it prints 'Finished' since it has reference. | |
| console.log('Finished'); | |
| } | |
| // In this scenario: | |
| // Have this qn because from your talk - 'Syncing Async' you mentioned that due to inversion of control they could potentially call the cbFn multiple times. | |
| // Wondering how that could happen? | |
| // The callback is called once the request completes right? Or is there a way a callback can be triggered multiple times once a request is complete? | |
| // What controls how many times the success callback will be called? |
getify
commented
Dec 3, 2015
- the second 'callbackFn' definition won't do anything.
- 'completeAsyncCheckout' is the only one who decides when and how many times the callback reference it receives will be called
@getify Great! When I tried it with setTimeout 'completeAsyncCheckout' received a reference to callbackFn. So, once it completed, it printed 'Finished' instead of the earlier 'Done'.
Is is fair to assume, the flow would be same for an async API request with callback as well? It does pass the reference only right?
Do you mean?
setTimeout(completeAsyncCheckout,..)
@getify Did a setTimeout(cbFn, 3000);
It makes sense that setTimeout is a web api and it ends up calling the updated fn after 3000ms.
Will such a thing happen if I passed a cbFn to an external async API request via completeAsyncCheckout (which takes a fews secs as well)?
no, because once you pass the reference to your orig function to somewhere elsr, if you then re-assign your reference to a new function, the passed reference still refers to the orig function.
@getify Gotcha.. Thanks a lot. You're my JS hero!