8
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Promiseとasync functionの書き換え

Posted at

async修飾子をfunctionにつけるとPromiseを返す関数になる。

async修飾子の付いたfunctionで値をreturnするとpromiseでresolveしたときと同じ。
以下のコードのsuc1,2,3は同じ動作をする関数になる。

function suc1() {
  return new Promise((resolve) => {
    resolve('suc1');
  })
}

function suc2() {
  return Promise.resolve('suc2');
}

async function suc3() {
  return 'suc3';
}

async function suc() {
  console.log(await suc1());
  console.log(await suc2());
  console.log(await suc3());
}

// suc()の実行結果
// suc1
// suc2
// suc3

async修飾子の付いたfunctionで例外を投げるとrejectしたときと同じ動作をする。


function err1() {
  return new Promise((resolve, reject) => {
    reject('err1');
  })
}

function err2() {
  return Promise.reject('err2');
}

async function err3() {
  throw 'err3';
}

async function err() {
  try {await err1()} catch(e) {console.log(e)}
  try {await err2()} catch(e) {console.log(e)}
  try {await err3()} catch(e) {console.log(e)}
}

// err()の実行結果
// err1
// err2
// err3
8
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?