"delay" handler for definitions with async calls #1078
Closed
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Some modules do need to perform asynchronous calls to be fully initialized.
In example :
IndexDB calls https://developer.mozilla.org/en/docs/IndexedDB
Ajax requests
Blob builders
Custom methods with asynchronous tasks
To get sure that the asynchronous calls are performed before the defined events are triggered, it is possible to use a plugin that will manually handle those special cases. The problem is that to delay the "define" event, the plugin has to used for each require which creates redundancy across secondary modules depending on the first module requiring async calls. It would be more logical if the async nature of a module was in its definition.
The idea would be to not only load modules asynchronously but also to get their value asynchronously.
The best idea I found was to create a new special handler ( like "require", "exports" or "module" ) called "delay" and being a callback function for the return value.
For example it would look this way :
define(["delay"], function ( delay ) { // depends on the "delay" handler : the value will be returned asynchronously
var Module = ... ;
setTimeout(function(){ //Some asynchronous actions
delay(Module) ; //This does actually returns the Module's value and triggers the "defined" event.
//It's transparent, just as if the loading time over the network was a bit longer.
},1000);
return Module ; //This does not do anything because delay is active
});
This was achieved with only a few lines of code (check the diff) and could offer a useful feature to get a better structured module when its initialization does not simple rely on the load of the file.
PS : I do have a CLA with Dojo