Last active
December 14, 2020 15:47
-
-
Save runceel/ffea096f9e30fdea7d65bd71a7932f12 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 出力 | |
now loading | |
now loading | |
now loading | |
done { index: 1, result: filter2: src image } | |
done { index: 0, result: filter1: src image } | |
done { index: 2, result: filter3: src image } | |
filter1: src image | |
filter2: src image | |
filter3: src image | |
*/ | |
async function main() { | |
// filter の元 | |
const filter = async(image: string, filterName: string, interval: number) => { | |
return new Promise<string>((resolve) => setTimeout(() => resolve(`${filterName}: ${image}`), interval)); | |
} | |
// 画像処理はめんどくさいので文字列加工をフィルターに見立てて3つ作る | |
const filter1 = (image: string) => filter(image, 'filter1', 3000); | |
const filter2 = (image: string) => filter(image, 'filter2', 2000); | |
const filter3 = (image: string) => filter(image, 'filter3', 5000); | |
// ページに見立てたクラス | |
class Page { | |
private images: string[] | |
constructor( | |
// 元データ | |
public sourceImage: string, | |
// このページで扱うフィルター | |
public filters: ((image: string) => Promise<string>)[]) { | |
// フィルターと同じ要素数だけ結果格納用配列を用意しておく | |
this.images = [...Array(filters.length)].map(_ => 'now loading'); | |
} | |
async applyFilters() { | |
// とりあえず手抜き実装で全フィルターを適用して、終わったものから終わった時の処理をする | |
await Promise.allSettled( | |
this.filters.map(async (f, i) => { | |
const result = await f(this.sourceImage); | |
this.images[i] = result; | |
this.update(i, result); | |
})); | |
} | |
// 指定要素のインデックスの処理結果を表示 | |
update(index: number, result: string) { | |
console.log(`done { index: ${index}, result: ${result} }`); | |
} | |
// 全データ表示 | |
printAll() { | |
for (const image of this.images) { | |
console.log(image); | |
} | |
} | |
}; | |
// ページ作って、処理前の状態を印字して、フィルター適用(途中経過表示)して | |
// フィルター適用が全部終わったら再度全部表示してみる | |
const page = new Page('src image', [filter1, filter2, filter3]); | |
page.printAll(); | |
await page.applyFilters(); | |
page.printAll(); | |
} | |
main(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment