2014-07-06 46 views
1

我寫在DART的功能,將在瀏覽器端的索引數據庫,當我發現我不得不從內部函數中返回一個外部函數值刪除對象:如何從內部函數/流偵聽器中返回函數值?

Future<bool> delete() { 
    Transaction tx = db.transactionStore(storeName, "readwrite"); 
    ObjectStore os = tx.objectStore(storeName); 
    os.delete(_key); // returns blank future, modifies tx 

    // This is not correct, but shows the idea: 
    if (tx.onComplete) {return true;} 
    if (tx.onError) {return false;} 
} 

這函數是我用來保存和加載到索引數據庫的類的方法。 當刪除操作成功或失敗時,我希望此函數返回truefalse或包含它的Future對象。但是,瓶頸是os.delete(_key);聲明:它返回未來,但刪除操作的實際成功或失敗由tx.onCompletetx.onError提供。這兩個對象都是流,所以我需要創建一個處理來自他們的事件匿名函數:

tx.onComplete.listen((e){ 
    return_to_outer_function(true); 
}); 
tx.onError.listen((e){ 
    return_to_outer_function(false); 
}); 
return_to_outer_function(bool) { 
    return bool; // doesn't work 
} 

正如你可以看到,當我創建匿名函數,返回語句不再完成了方法,但其內功能。我可以讓內部函數調用其他函數,但是那些其他函數具有自己的返回語句,它們不會將結果返回給整個方法。

我嘗試了設置臨時變量並定期檢查它們的方法,但這是一個非常不雅的解決方案,我不想使用這個方法,不僅僅針對潛在的錯誤,而且因爲它會佔用單線程事件循環。

是否有可能從內部函數返回一個值到外部函數?或者還有其他更好的方法從一組流中是否存在事件中獲得價值?還是有另一種使用IndexedDB的方法可以避免這個問題?

回答

4

您可以使用這個Completer

Future<bool> delete() { 
    Completer completer = new Completer(); 
    Transaction tx = db.transactionStore(storeName, "readwrite"); 
    ObjectStore os = tx.objectStore(storeName); 

    tx.onError.first((e){ 
    //return_to_outer_function(false); 
    completer.complete(false); 
    }); 
    tx.onComplete.first(bool) { 
    //return bool; // doesn't work 
    completer.complete(true) 
    } 
    os.delete(_key); // register listeners and then do delete to be on the save side 

    return completer.future; 
} 

你再這樣稱呼它

delete().then((success) => print('succeeded: $success')); 

也看到https://api.dartlang.org/apidocs/channels/be/dartdoc-viewer/dart:async.Completer

相關問題