2013-03-05 90 views
0

我使用Jaydata作爲HTML5 indexedDB的API。我在indexedDB中有一個表,我需要遞歸查詢。整個過程完成後,我需要回調。以下是遞歸函數。當一切都完成時,我需要回電。在遞歸異步調用中處理回調

function getData(idValue) { 
    myDB.MySplDB 
     .filter(function(val) { 
      return val.ParentId == this.parentId; 
     }, {parentId: idvalue}) 
     .toArray(function(vals) { 
      if(vals.length < 1) { 
       // some operation to store the value 
      } else { 
       for (var j=0;j<vals.length;j++) { 
        getData(vals[j].Id); 
       } 
      } 
     }); 
} 

添加.done(function(){...});.toArray不起作用,因爲它被完成之前調用。

回答

1

(聲明:我JayData工作)

要等待整個的結束過程中你需要使用承諾。你總是必須回報一個承諾。在循環中變得棘手,返回超級承諾。因此,代碼應該是這樣的:

function getData(idValue) { 
    return myDB.MySplDB 
    .filter(function(val) { 
     return val.ParentId == this.parentId; 
    }, {parentId: idvalue}) 
    .toArray(function(vals) { 
     if(vals.length < 1) { 
      // some operation to store the value 
      // important: return a promise from here, like: 
      return myDB.saveChanges(); 
     } else { 
      var promises = []; 
      for (var j=0;j<vals.length;j++) { 
       promises.push(getData(vals[j].Id)); 
      } 
      return $.when.apply(this, promises); 
     } 
    }); 
} 

getData(1) 
.then(function() { 
     // this will run after everything is finished 
}); 

備註:

  1. 這個例子使用jQuery的承諾,所以你需要的jQuery 1.8+ $。當使用可變參數,因此我們需要的應用

  2. 這可以帶q承諾工作有稍微不同的語法

+0

在部分// //存儲值的一些操作,我不會將值存儲在數據庫中。我將這些存儲在一個數組中。目的是獲得所有沒有孩子的元素,即對象的Id不是任何其他對象的parentId。 – Prabhat 2013-03-05 15:30:36

+0

還有什麼我必須返回而不是'return myDB.saveChanges(); '如果我沒有將值存儲在數據庫中? – Prabhat 2013-03-05 15:38:25

+0

在這種情況下,您可以返回任何內容,例如返回true; – 2013-03-05 15:46:10

0

這個僞代碼在你的情況下是否有意義?

var helper = function (accu) { 
// Take an id from the accumulator 
// query the db for new ids, and in the db query callback : 
    // If there is child, do "some operation to store the value" (I'm not sure what you're trying to do here 
    // Else add the child to the accumulator 
    // if accu is empty, call the callback, it means you reached the end 

的getData()會調用這個助手包含第一ID蓄能器,並最終回調