1
我的函數必須創建一個目錄,並將整個文件夾層次結構從另一個目錄複製到這個新目錄中。所有的操作都是異步完成的,但是我希望這個函數返回一個Future,當我調用.then(result)時,它將完成所有的異步工作。我應該在這個Future系列函數中把completer.complete()放在哪裏?
但我不知道我應該把我的completer.complete()
達到那個位置。
Future<Directory> createCopyDirectory(Directory directoryToCreate){
Completer<Directory> completer = new Completer<Directory>();
completer.complete(
directoryToCreate.create().then((directory){
Directory contentToCopy = new Directory(globalPathOfDirectoryToCopy);
List<Future> creatingContent = new List<Future>();
contentToCopy.list(recursive:true, followLinks:false).forEach((f){
if (f is File){
File fileToCreate = new File(f.path.replaceFirst('pages', userID));
creatingContent.add(fileToCreate.create(recursive:true).then((_){
f.readAsString().then((fileContent){
fileToCreate.writeAsString(fileContent);
});
}));
}
});
return Future.wait(creatingContent).then((_){ return directoryToCreate;});
})
);
return completer.future;
}
我準確的,我的功能工作像預期的,但是,如果我嘗試在then()
調用直接訪問我應該在這個功能所創建的內容,如,飛鏢給我的厚望像我有沒有創建了內容。所以completer.complete()
肯定放置不好,並且在創建內容之前先打電話then()
。
我試過了的completer.complete()
或return directoryToCreate
替換completer.complete(directoryToCreate)
但結果是一樣的。
對於在這種情況下構建合適的基於Future的功能,我有點困惑。
感謝,順便說一下! – fandegw 2015-02-23 16:14:55
我更新了我的答案(只有第一部分)。在'contentToCopy'和'.then'之前有一個額外的'return','foreEach'末尾有一個'...' – 2015-02-23 16:28:34
當你評論它時,我發現它是正確的,非常感謝你的大腦工作,它促使我發現問題更具活力 – fandegw 2015-02-23 16:34:26