1
0

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 5 years have passed since last update.

JavaScript Promise備忘録

Posted at

概要

JavaScriptのPromiseを使ったサンプルコードのメモ。

fnメソッドの引数を変更する事によって、resolveを返す時とrejectを返す時の動作確認も可能。動作確認はRepl.itが便利。

e.g.
resolveを返したい場合: fn('Success')
rejectを返したい場合: fn('Fail')
※rejectを返す場合はresolveを返す引数`Success`以外であれば何でもよい。

async/await

let count = 0

const fn = (arg) => {
  return new Promise(function(resolve, reject) {

    count++

    if (arg === 'Success') {
      resolve(`${count}回目 Success!`)
    } else {
      reject(`${count}回目 failed...`)
    }
  })
}

async function fnAsync() {
  try {
    const fn1 = await fn('Success')
    console.log(fn1)
    
    const fn2 = await fn('Success')
    console.log(fn2)
    
    const fn3 = await fn('Fail')
    console.log(fn3)
  } catch (e) {
    console.log(e)
  }
}

fnAsync()

then/catch

let count = 0

const fn = (arg) => {
  return new Promise(function(resolve, reject) {

    count++

    if (arg === 'Success') {
      resolve(`${count}回目 Success!`)
    } else {
      reject(`${count}回目 failed...`)
    }
  })
}

fn('Success').then(data => {
  console.log(`${data}`)
  return fn('Fail')
}).then(data => {
  console.log(`${data}`)
  return fn('Success')
}).then(data => {
  console.log(`${data}`)
}).catch(data => {
  console.log(data)
})
1
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?