How do I use promises to call a function after a previously called function has been finished?
For example, I want to load a script dynamically and call a function declared within the script. I did that without promises and got a function not found error. Any help with how to use promises to solve this kind of problem?
My JS code is as below:
jQuery ( document ). ready ( function ()
{
// setup option bar
addScript ("../js/optionBar.js") ; // add script dynamically
setupOptionBar ("WatchDog") ; // function declared in optionBar.js
} ) ;
function addScript ( url )
{
var script = document. createElement ("script") ;
script. src = url ;
document. head. appendChild ( script ) ;
}
Other options would be to include JS statically or declare function in main JS. But, I want to know how this can be done with promises as this kind of problem is faced regularly while coding in JS.
Edit:
Despite the current problem being solved, I still got the same question. Let's look at it with another example.
jQuery ( document ). ready ( function ()
{
jQuery ( div ). css ( { "height" : "200px" } ) ; // modifying heights of 30 divs
jQuery ("#div30"). html ( jQuery ("#div30"). css ("height") ) ; // should put 200 in #div30 but 100 appears as modification is still in progress
} ) ;
How would one tackle such a problem? Because, I am technically supposed to wait for the above statement to execute...
Edit#2:
The task is to add event handler to all events starting with certain ID. During execution, handler is added to all events but for every handler only the description of last element is shown. My understanding tells me its because of JS's asynchronous nature. Please, help...
JS Fiddle: http://jsfiddle.net/xpvt214o/707184/
jQuery ("[id^='WTM_appOptionTitle_']"). each ( function ()
{
module = jQuery ( this ). attr ("id"). replace ("WTM_appOptionTitle_" , "") ; // store name of module
jQuery ("#WTM_appOptionTitle_" + module ). hover (
function ()
{
jQuery ("#WTM_appOptionDescription_" + module ). addClass ("wtm_appoptiondescriptionshow") ; // module has the value of last module only when this statement is executed
} ,
function ()
{
jQuery ("#WTM_appOptionDescription_" + module ). removeClass ("wtm_appoptiondescriptionshow") ;
} ) ;
} ) ;
Thanks everyone for your patience and help...