本文介绍了承诺只发射一次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下承诺是否只有一次触发是否有任何理由?
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
})
推荐答案
因为承诺只会触发一次。承诺被创建/初始化,然后结算,一旦结算,永远不会解决或重新解决。调用解决
或拒绝
第二个(第三个,第四个......)时间是无操作。 (有些人认为它应该是一个错误,但事实并非如此。)承诺不是事件,它们不能再发生。因此,对于该代码正在做什么,承诺不是正确的工具。
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.
这篇关于承诺只发射一次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!