0
1

More than 3 years have passed since last update.

promise、asyncとawaitについて(自分用)

Posted at
  • 非同期処理を行ったあとに、処理を実行したい
  • 500ミリ秒後に、helloを実行し、そのあとにworldを実行したい
setTimeout(() => console.log('hello'), 500);
console.log('world');
  • worldのあとに、helloが実行されてしまった
  • さらにコールバックを使って実現してみよう!
setTimeout(() => {
 console.log('hello');
  setTimeout(() => {
    console.log('world');
  }, 500);
}, 500);
  • できたけど、ネスト化していてわかりづらい(コールバック地獄)
  • promiseでわかりやすくかけるらしい
const promise = new Promise((resolve, reject) => {
    setTimeout(() => { 
        console.log('hello');
        resolve();
    }, 500);
});
promise.then(() => console.log('world!'));
console.log('yeah!'); // ここが実行されたあとに、上の2つが実行される
  • わかりやすくなった!
  • asyncとawaitを組み合わせることでより簡潔にかけるらしい
async function helloWorld(text) {
  const promise = new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(text);
    }, 5000);
  });
  const val = await promise; // awaitでpromiseの終了を待つ
  console.log(val);
  console.log('world!');
}

helloWorld('hello');
console.log('Yeah'); // ここが実行されたあとに、上の処理が実行される
  • より処理の流れがわかりやすくなった
0
1
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
1