2013-06-01 15 views
0

我有一個綁定到Google地圖上的鼠標點擊事件的函數。由於功能的性質,完成處理可能需要一些時間(取決於連接速度,0.1秒-2秒)。本身並不是什麼大問題,但是如果用戶點擊開心,這可能會導致問題,並且以後的調用與前一次調用有些相關。處理和等待以前的JavaScript調用完成

什麼是最好的方式讓後來的電話等待以前的電話完成?或者甚至是處理以前通話失敗的最佳方式?

我看過執行以下操作:

  • 使用自定義.addEventListener(Link)
  • 使用while循環等待已處理
  • 使用一個簡單的,如果前面的一個檢查語句,如果前一個需求要重新運行
  • 使用其他形式的回調

現在針對上下文的一些示例代碼:

this.createPath = function(){ 
    //if previous path segment has no length 
    if (pathSegment[this.index-1].getPath().length === 0){ 
     //we need the previous path segment recreated using this same function 
     pathSegment[this.index-1].createPath(); 
     //now we can retry this path segment again 
     this.createPath(); 
    } 
    //all is well, create this path segment using Google Maps direction service 
    else { 
     child.createPathLine(pathSegment[this.index-1].getEndPoint(), this.clickCoords); 
    } 
} 

自然,此代碼會像瘋狂一樣循環並創建許多請求。

回答

0

這是一個很好的用例承諾

他們這樣的工作(使用jQuery的承諾例子,但也有承諾其他的API,如果你不想使用jQuery):

function doCallToGoogle() { 
    var defer = $.Deferred(); 

    callToGoogleServicesThatTakesLong({callback: function(data) { 
     defer.resolve(data); 
    }}); 

    return defer.promise(); 
} 

/* ... */ 
var responsePromise = doCallToGoogle(); 

/* later in your code, when you need to wait for the result */ 
responsePromise.done(function (data) { 
    /* do something with the response */ 
}); 

的好處是,你可以鏈的承諾:

var newPathPromise = previousPathPromise.then(
     function (previousPath) { /* build new path */ }); 

看看到:

總結的承諾是在使用回調,這對於控制流非常有用的對象抽象(鏈接,等待所有的回調,避免大量的回調嵌套)。

+0

謝謝迭戈!我做了一些研究這些選項,他們似乎很有希望。但是,在下次運行之前,我沒有看到一種簡單的方法來構建對先前請求完成的依賴。在第二部分中,你提到了那些我認爲我可能會用到的東西。從我做的測試看來,你甚至可以標記,然後在承諾解決之後。也許讓虛擬解決方案延遲並使用。然後排隊。這甚至會有道理嗎?它對我來說似乎不是很乾淨。 –