Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Is there any reason why the promise below is only firing once?

console.log('start')

var Promise = require('bluebird')
var onoff = require('onoff')
var Gpio = onoff.Gpio
var button = new Gpio(4, 'in', 'both')

var buttonWatchAsync = function (button, desiredValue) {
  return new Promise (function (resolve, reject) {
    return button.watch(function(err, value) {
      if (err) return reject(err)
      if (typeof desiredValue === 'undefined') return resolve(value)
      if (desiredValue === value) return resolve()
    })
  })
}

buttonWatchAsync(button)
  .then(function (value) {
    console.log('fired promise')
    console.log(value)
  })
  .catch(function (err) {
    throw err
  })
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
496 views
Welcome To Ask or Share your Answers For Others

1 Answer

Because promises only fire once. A promise is created/initialized, and then settled, and once settled can never be un-settled or re-settled. Calling resolve or reject a second (third, fourth, ...) time is a no-op. (Some believe it should be an error, but it isn't.) Promises are not events, they cannot recur. So for what that code is doing, a promise isn't the right tool.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...