JSFiddle - React, Tailwind, and code Playground

by yshrkn

JavaScript

function asyncFunc() {
  return new Promise((resolve, reject) => {
    setTimeout(() => resolve('成功'), 2000)
  })
}

async function f() {
 	try {
    const message = await asyncFunc();
    console.log(message);
  } catch(e) {
	  console.log('try catchでエラー');
	}

	// .catch()を使用した例外キャッチも書ける
	//await asyncFunc().catch((val) => { console.log(val); });
}

console.log('Before');
f();
console.log('After');

/*** resolve('成功') の場合***/
// Before
// After
// 成功 (実行から2秒後)


/*** reject('失敗') の場合***/
// Before
// After
// try catchでエラー (実行から2秒後)