「time」「text」を引数にした「timer()」関数です。
const timer = function(time, text) { return new Promise(function(resolve) { setTimeout(function() { console.log(text); resolve(); }, time); }); };
先ほどの関数を、アロー関数で短く書き、実際に使用します。
const timer = (time, text) => new Promise(resolve => { setTimeout(() => { console.log(text); resolve(); }, time); }); timer(500, '処理1') .then(function() { return timer(600, '処理2'); }) .then(function() { return timer(700, '処理3'); }) .then(function() { return timer(800, '処理4'); }) .then(function() { console.log('終了'); });
「Promise」を利用した処理を、アロー関数で短く書き、さらに短く記述します。
const timer = (time, text) => new Promise(resolve => { setTimeout(() => { console.log(text); resolve(); }, time); }); timer(500, '処理1') .then(() => timer(600, '処理2')) .then(() => timer(700, '処理3')) .then(() => timer(800, '処理4')) .then(() => console.log('終了'));
処理1 処理2 処理3 処理4 終了
種類 | 無料版 | 有料版 |
---|---|---|
頒布先 | Amazon | Booth |
形態 | Kindle電書 | PDF+コード |
価格 | 0円 | 500円 |
目的 | 知識普及 安価に閲覧 | 作者応援 自由な環境で閲覧 |
DRM | あり | なし |
マンガ | ○ | ○ |
コラム | ○ | ○ |
実行可能な コード | × | ○ |