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

Categories

0 votes
512 views
in Technique[技术] by (71.8m points)

javascript - Promise is only firing once?

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

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

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...