Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
518 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...