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 |
'use strict'; const errMsgTimeout = "タイムアウト失敗"; const createTimeoutPromise = (ms, callback, isErr = false) => { return new Promise((resolve, reject) => { if (isErr) { reject(errMsgTimeout); } setTimeout(() => { resolve(callback()); }, ms); }); }; const main = async() => { const ret1 = await createTimeoutPromise(10, _ => "10秒").catch(a => a); const ret2 = await createTimeoutPromise(100, _ => "100秒").catch(a => a); const ret3 = await createTimeoutPromise(30, _ => "30秒", true).catch(a => a); const ret4 = await createTimeoutPromise(20, _ => "20秒").catch(a => a); console.log(ret1); console.log(ret2); console.log(ret3); console.log(ret4); }; main(); |
1 2 3 4 |
10秒 100秒 タイムアウト失敗 20秒 |