LoginSignup
5
2

More than 3 years have passed since last update.

【同期処理】async/awaitできない(待ってもらえない)問題【Node.js】

Posted at

Node.jsが親切設計すぎて、時間がかかる処理をしている間に勝手にその後の処理に進んでしまって困りました。

そこでasync/awaitしたのですがなかなか待ってもらえず…

こちらの回答者さんの回答を拝見し、解決しました。→(https://teratail.com/questions/131373)

記録します。

できなかった時のプログラム

index.js
()
async function a(){
  //ちょっと時間がかかる処理

  return '2'
}

async function main(){
  const number = await a()
  console.log(number)
  console.log("numberを表示した後")
}

実行結果です↓

numberを表示した後
2

実行結果がかわってないー(「2→numberを表示した後」、という順番にしたい)

できた時のプログラム

index.js
()
//--------returnで囲っちゃった!------------
function a(){
  return new Promise((resolve, reject) => {
    //ちょっと時間がかかる処理
    resolve('2')
  }
}

async function main(){
  const number = await a()
  console.log(number)
  console.log("numberを表示した後")
}
main()

実行結果です↓

2
numberを表示した後

やったー!

5
2
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
5
2