非同期処理も順番守って出力させたい
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 |
class PrinterBuffer { constructor(id) { this.isConsole = (id === undefined) this.ps = [] if (this.isConsole) { this.lineFeedMark = '\n' } else { this.lineFeedMark = '<br>' this.element = document.getElementById(id) } } output(s) { if (this.isConsole) { console.log(s) } else { this.element.innerHTML = s } } flush() { Promise.all(this.ps).then(results => { let s = ""; for (const result of results) { s += result + this.lineFeedMark } this.output(s) }) } push(s) { this.ps.push(new Promise(resolve => { resolve(s) })) } pushPromise(promise, writeBack) { this.ps.push(new Promise(resolve => { promise.then(result => { resolve(writeBack(result)) }) })) } pushPromiseArray(promiseArray, arrayWriteBack) { this.ps.push(new Promise(resolve => { Promise.all(promiseArray).then(results => { resolve(arrayWriteBack(results)) }) })) } } function main() { // const p = new PrinterBuffer('p1') const p = new PrinterBuffer() const getPromiseVar = (len) => { const ps = [] for (var i = 0; i < len; i++) { ps.push(new Promise(resolve => { setTimeout(() => { resolve(i) }, 0); })) } return ps } const getPromiseLet = (len) => { const ps = [] for (let i = 0; i < len; i++) { ps.push(new Promise(resolve => { setTimeout(() => { resolve(i) }, 0); })) } return ps } const len = 5; p.push("first") p.pushPromise(new Promise(resolve => { resolve("pushPromise() first"); }), ret => ret) p.pushPromiseArray(getPromiseVar(len), rets => rets) p.push("second") p.pushPromise(new Promise(resolve => { resolve("pushPromise() second"); }), ret => ret) p.pushPromiseArray(getPromiseLet(len), rets => rets) p.push("third") p.pushPromise(new Promise(resolve => { resolve("pushPromise() third"); }), ret => ret) p.flush() } main() |
1 2 3 4 5 6 7 8 |
first pushPromise() first 5,5,5,5,5 second pushPromise() second 0,1,2,3,4 third pushPromise() third |