简体   繁体   English

尝试使Javascript函数同步运行

[英]Try to get Javascript functions to run Synchronously

I'm having trouble with the following code snippet. 我在使用以下代码段时遇到麻烦。 My init method needs to run and complete the getLocation() function before the initializeMapp() and geoListen() can run. 我的init方法需要先运行并完成getLocation()函数,然后才能运行initializeMapp()和geoListen()。 I have rsvp.js linked as a resource, but not quite sure how to implement. 我将rsvp.js链接为资源,但不太确定如何实现。 I also tried the jQuery $when.done method. 我还尝试了jQuery $ when.done方法。 Any help is appreciated. 任何帮助表示赞赏。

jQuery Method: jQuery方法:

//initial page load method
function init() {

    //get user location then builds map and listens to database
    $.when(getLocation()).done.(function () {

       //build map now that you have user location
        initializeMap();

       //Starts listening to database changes
       geoListen();

    })

}

RSVP method: RSVP方法:

 //initial page load method
 function init() {

      //get user location then builds map and listens to database
     getLocation().then(function () {

     //build map now that you have user location
     initializeMap();

     //Starts listening to database changes
     geoListen();

  })

 }   

you can make your getLocation function accept callbacks and execute them when getLocation finishes 您可以使您的getLocation函数接受回调并在getLocation完成时执行它们

getLocation = function(cb1, cb2) {
  // when done 
  cb1()
  cb2()
}

function init() {
  getLocation(initializeMap, geoListen)
}

or you can pass an array of callback references and loop through them in getLocation and call them 或者,您可以传递一组回调引用,并在getLocation遍历它们,然后调用它们

alternatively you can use Q.js and return a promise from getLocation 或者,您可以使用Q.js并从getLocation返回一个Promise

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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