孤独プログラマー譚

孤独死が近い。

JavaScript Promiseとasyncの書き換え

以下の2つ、Promiseとasyncメソッドは書き換えられる。

foo() {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve('foo_value')
    }, 1000)
  })
}
async bar() {
  await new Promise((resolve) => {
      setTimeout(resolve, 1000)
  })
  return 'bar_value'
}


メソッドから返却されたPromiseオブジェクトはawaitできる。
asyncメソッドの返却値もPromiseオブジェクトとなる。

const val1 = await this.foo()
console.log(val1) // foo_value
const val2 = await this.bar()
console.log(val2) // bar_value


awaitでなく、then()メソッドでも対応できる。
asyncメソッドの返却値(Promiseオブジェクト)からthen()メソッドを使用することもできる。

const promise1 = this.foo()
promise1.then(val => console.log(val)) // foo_value
const promise2 = this.bar()
promise2.then(val => console.log(val)) // bar_value