在我的旅程打字稿,我被告知,阻塞調用永遠不應該異步代碼內進行。
我還使用了生成器,因爲它們使目錄遍歷變得容易並避免用完堆棧空間。
然而,當我結合異步代碼(在這種情況下:readdir
)與發電機,編譯器會抱怨說產量僅能在發電機使用,導致我覺得編譯器不能夠結合關閉,生成器和異步代碼,一氣呵成。
function *yyyymmGenerator(dir: string, props: Props) {
const fs = require("fs");
const yyyy = props.range.getUTCFullYear().toString();
const mm = props.range.getUTCMonth().toString();
const start = `${yyyy}-${mm}`;
const files = fs.readdir(dir, function(err, files) {
for (let i = 0; i < files.length; i++) {
const file: string = files[i];
if (file.localeCompare(start) >= 0) {
const d = `${dir}/${file}`;
yield file;
}
}
});
}
error TS1163: A 'yield' expression is only allowed in a generator body.
問題
這將是在這樣的情況下推薦的最佳做法?
如果我簡單地考慮一切同步,阻止代碼但在承諾內「包裝」呼叫,那會好嗎?
見http://stackoverflow.com/questions/41326217/js-how-to-use-generator-and-回報率低 –