3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Promise~JavaScript

Last updated at Posted at 2020-08-24

JavaScroptのPromise処理についてちょっと理解できた気がしたのでアウトプットとして。

では早速

基本的な書き方

function test(value) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (value) {
        resolve(value)//成功
      } else {
        reject('値がありません')//失敗
      }
    }, 3000)
  })
}

//実行
test('Hello').then(response => {
  console.log(response)//結果 setTimeoutの処理の後(約3秒後)に Hello となる
}, error => {
  console.log(`エラー:${error}`)
})

Promise処理の関数を作りその引数に値を入れたりして
処理が完了(成功)したら__resolve()
今回の場合だと引数に
'Hello'__と文字列を入れているのでresolve()の方の処理になる。
これを引数なしで実行すると__reject()の方の処理になる。
resolve()に引数を入れると、その引数の値を
.then()__で受け取れる。

この様にPromiseを使う事で同期処理の様な形で処理ができる。

.then()の中でreturnして繋ぐこともできる

test('Hello').then(response => {
  console.log(response)//約3秒後に Hello
  return test('Bye')
}).then(response => {
  console.log(response)//更に3秒後に Bye
  return test('Wao!!')
}).then(response => {
  console.log(response)//更に3秒後に Wao!!
})

結果、上記の処理は全体で約9秒かかる事になる。

複数の処理をまとめて実行 Promise.all

Promise.all([
  test('Hello'),
  test('World'),
  test('!!')
]).then(response => {
  console.log(response)//結果 [ 'Hello', 'World', '!!' ]
})

Promise.all__には配列で渡す。
全ての処理が完了したら
.then()に値が入る。
この時
.then(response)__には配列として値が返ってくる

普通に書いた場合

function sample1() {
  setTimeout(() => {
    console.log('Promise-1')
  }, 1800)
}
function sample2() {
  setTimeout(() => {
    console.log('Promise-2')
  }, 1000)
}
function sample3() {
  setTimeout(() => {
    console.log('Promise-3')
  }, 600)
}

sample1()
sample2()
sample3()

//結果 Promise-3 Promise-2 Promise-1

間に時間のかかる処理等(非同期処理)があったりすると順番通りにいかない

上記を__Promise__で書くと

function sample1() {
  return new Promise((resolve) => {
    setTimeout(() => {
      console.log('Promise-1')
      resolve()
    }, 1800)
  })
}
function sample2() {
  return new Promise((resolve) => {
    setTimeout(() => {
      console.log('Promise-2')
      resolve()
    }, 1000)
  })
}
function sample3() {
  return new Promise((resolve) => {
    setTimeout(() => {
      console.log('Promise-3')
      resolve()
    }, 600)
  })
}

sample1()
  .then(() => sample2())
  .then(() => sample3())
 //結果 Promise-1 Promise-2 Promise-3

と順番通りに処理できる。

async~await

async function test() {
    await sample1()
    await sample2()
    await sample3()
  }
  test()

結果は同じawaitで待つという感じになるみたい
それとasyncを関数の前に
まだ理解が足りてないのでまた別で書こうと思います。

間違いがあれば指摘いただけると嬉しいです!

async,awaitもちゃんと覚えなければ、、、

3
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
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?