1
0

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.

async/awaitとpromiseの対比

Posted at

#はじめに

Promise と async/await について勉強した際のメモです

#async/await と promise

const getDataPromise = (num) => new Promise((resolve, reject) => {
    setTimeout(() => {
        typeof num === 'number' ? resolve(num * 2) : reject('error!!!!!!!!!!!!!!!!!')
    }, 2000)
})

上のようなpromiseを返すgetDataPromise()があったとして、


const processData = () => new Promise((resolve, reject) =>{
    getDataPromise(1).then((data) => {
        return getDataPromise(data)
    }).then((data) => {
        resolve(data)
    }).catch((err) => {
        reject(err)
    })
})

これは

const processData = async () => {
    let data = await getDataPromise(1)
    data = await getDataPromise(data)
    return data
}

と同じ

asyncってのはつまるところ、戻り値をpromiseとして返すってこと

上の例でawaitしている関数でerrorが生じた場合、水面下で throw new ErrorしてくれるようになっているのでprocessData()を呼び出すときに

processData().then((data) => {
    //なんかの処理
}).catch((error) => {
    //エラー処理
})

こんな感じでcatch()してあげればOK

1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?