LoginSignup
0
0

More than 1 year has passed since last update.

Async/Awaitを完全に理解した

Last updated at Posted at 2021-11-07

初めに

ちょっとできるになりたい 伝わるかな?
1年前は長時期よくわからなかったAsync/Awaitさんですが、この度理解できましたので、Qiitaの記事を更新します。
Asyncってなんて読むか知ってます?
「エイシンク」です。 「アシンクじゃないよ!!」

Async/Awaitとは

Promiseの結果がreturnされるまで一時停止する
Asyncの関数の中でしか使えない

基本

// この関数はPromiseを返す関数になる
async function() {}
// awaitはPromiseの結果が返るまえ一時停止する
// awaitはasyncで定義した関数の中で使える
await Promise処理

実例

  • Promiseを返す関数を定義
  • asyncが頭にある関数の中で上記の関数をawaitを頭につけて実行する
  • asyncが頭にある関数を実行()

上記の手順で、asyncの中の関数は同期処理のように上から順に実行されるようになる

// promiseを返す関数を作成 returnを忘れずに
let time = () => {
  return new Promise((resolve) => {
    setTimeout(() => resolve("tee"), 1000)
  })
}


let myAsync = async () => {
  // resolveの結果がわかるまで停止できる
  const result = await time() // time()は上で定義したPromiseを返す関数
  
  // resultに値が入ったあと下記を実行
  console.log(result)
}

myAsync()

resolveの実引数を繋げる

const mypromise = () => {
  return new Promise((resolve) => {
    setTimeout(() => resolve("tee"), 1000)
  })
}

const main = async () => {
  // promiseと比べてreturnを書く手間がない
  console.log(await mypromise())
  console.log(await mypromise())
}

main()
0
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
0
0