LoginSignup
14
14

More than 5 years have passed since last update.

Javascriptの非同期処理を同期的に書く方法

Last updated at Posted at 2017-09-01

はじめに

Javascriptはシングルスレッド+同期的なプログラミング言語だが非同期処理が可能

シングルスレッド?

シングルスレッド
人-------------------

マルチスレッド
人-------------------
人-------------------
人-------------------

同期処理/非同期処理とは?

同期処理
処理の1つに時間のかかる処理があると、
その実行が完了するまで、次の行には進まない。

非同期処理
処理の1つに時間のかかる処理があると、
その終了を待たずに次の処理に進み、時間のかかる処理が終了したら通知する

非同期処理が可能?

export default {
  methods: {
    sleep (wait, result) {
      setTimeout(() => {
        console.log(value)
      }, wait)
    },
    setTimeoutIsAsync () {
      this.sleep(2000, 1)
      this.sleep(100, 2)
      this.sleep(1000, 3)
    },
  },
  mounted () {
    this.setTimeoutIsAsync()
  }
}

実行結果
2->3->1

Javascriptでは、setTimeoutやfsなど処理時間がかかる処理を行う場合、その処理が非同期で実行される。

シングルスレッドの証明

export default {
  methods: {
    sleep (wait, result) {
      setTimeout(() => {
        console.log(value)
      }, wait)
    },
    jsIsSingleThread () {
      this.sleep(1000, 1)
      for (let i = 0; i < 10000; i++) {
        console.log(i)
      }
    },
  },
  mounted () {
    this.jsIsSingleThread()
    console.log('completed')
  }
}

実行結果
0...10000->completed->1

this.sleepの実行は「0-10000」のループ処理終了後に行われる。
Javascriptはシングルスレッドなため、優先度が高く、重い処理が実行中の場合はその処理が終了してから非同期の処理が実行される。

Promiseを使って非同期処理を同期的に書く

export default {
  methods: {
    sleep (wait, result) {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          console.log(result)
        }, wait)
      })
    },
    syncSleepByUsingPromise () {
        this.sleep(2000, 1).then(
          () => this.sleep(100, 2)
        ).then((result) => {
          return this.sleep(1000, 3)
        }).catch((error) => {
          console.log(error)
        })
      },
  },
  mounted () {
    this.syncSleepByUsingPromise()
  }
}

実行結果
1->2->3

Async-Awaitを使って非同期処理を同期的に書く

こちらの方がより手続き的に書けるので使いやすい

export default {
  methods: {
    async sleep (wait, result) {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          console.log(result)
        }, wait)
      })
    },
    async syncSleepByUsingAsyncAwait () {
      await this.sleep(2000, 1)
      await this.sleep(100, 2)
      await this.sleep(1000, 3)
    },
  },
  mounted () {
    this.syncSleepByUsingAsyncAwait()
  }
}

実行結果
1->2->3

14
14
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
14
14