September 22, 2017

Promise の挙動確認

意図しない挙動の Promise

// promise.js
const hoge = () => {
  console.log('1')
  return Promise.resolve()
}

const wait = () => {
  setTimeout(() => {
    console.log('2')
    return Promise.resolve('Promise')
  }, 1000)
}

const fuga = msg => {
  if (typeof msg === 'undefined') {
    msg = 'World'
  }
  console.log('3')
  console.log(`Hello, ${msg}!`)
}

const main = () => {
  hoge()
    .then(wait)
    .then(fuga)
}

main()
$ node promise.js
1
3
Hello, World!
2

意図したとおりの Promise

// promise.js
const hoge = () => {
  console.log('1')
  return Promise.resolve()
}

const wait = () => {
  return new Promise(resolve => {
    setTimeout(() => {
      console.log('2')
      resolve('Promise')
    }, 1000)
  })
}

const fuga = msg => {
  if (typeof msg === 'undefined') {
    msg = 'World'
  }
  console.log('3')
  console.log(`Hello, ${msg}!`)
}

const main = () => {
  hoge()
    .then(wait)
    .then(fuga)
}

main()
$ node promise.js
1
2
3
Hello, Promise!

wait の setTimeout を Promise で包んだ。 まだよく掴めてないので JavaScript Promiseの本 読む必要がある。。

© kyokutyo 2017