「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
終了