Last active
August 29, 2015 14:26
-
-
Save stevenwcarter/5698c0c2bdc3e73ef8f2 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
gpio.read(pin, function(err, value) { | |
if (err) throw err; | |
console.log(value); | |
}); | |
function getX (callback) { | |
gpio.read(pin, function (err, value) { | |
if (err) throw err; | |
callback(value); | |
}); | |
} | |
// Say you wanted to log X or print it to the screen: | |
getX(function (x) { | |
console.log(x); | |
}); | |
printX(function (screen, x) { | |
// I just made up some screen function, this isn't a real thing. | |
screen.write(x); | |
}); | |
// Now lets do the same thing with promises | |
// https://www.promisejs.org/ | |
// https://functionwhatwhat.com/introduction-to-promises-in-javascript/ | |
function getX_withPromises () { | |
var defer = q.defer(); | |
gpio.read(pin, function (err, value) { | |
if (err) { | |
defer.reject(err); | |
} | |
defer.resolve(value); | |
}); | |
return defer.promise; | |
} | |
// Without "handling" the error | |
getX_withPromises().then(function (x) { | |
console.log(x); | |
}); | |
getX_withPromises().then(function (screen, x) { | |
screen.write(x); | |
}); | |
// Adding error handling | |
function handleError (err) { | |
throw err; | |
} | |
// Here you see that you can also just pass a function name and it will be handled. | |
// The "then" function takes two parameters: successfunction, errorFunction | |
// reject will pass to the errorFunction and resolve passes to successFunction | |
getX_withPromises().then(function (x) { | |
console.log(x); | |
}, handleError); | |
getX_withPromises().then(function (screen, x) { | |
screen.write(x); | |
}, handleError); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment