-
Notifications
You must be signed in to change notification settings - Fork 286
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Question about promises #158
Comments
Nope - promises always need a callback function as the argument. If you find you're using repetitive, similar promises, you could make the promise creating code into a function, though. For example, you could change this: new Promise((resolve, reject) => { setTimeout(resolve, 1000) })
.then(function() { /* do something */ })
.then(function() { return new Promise(function() { setTimeout(resolve, 1000) }) })
.then(function() { /* do something */ }) Into this: function delay(ms) {
return function() {
return new Promise(function(resolve, reject) {
setTimeout(resolve, ms)
})
}
}
delay(1000)()
.then(function() { /* do something */ })
.then(delay(1000))
.then(function() { /* do something */ }) In the future you'll be able to use async/await to make the code generally simpler: function delay(ms) {
return new Promise(function(resolve, reject) {
setTimeout(resolve, ms)
})
}
async function main() {
await delay(1000)
/* do something */
await delay(1000)
/* do something */
}
main() But async/await isn't part of the standard yet, and isn't implemented into Node.js for now anyways (though you can use things like Babel to compile programs that use features like async/await). You can read more about async/await here. |
Interesting thank you, still the bit of boilerplate but feels much more clean. |
There is a pull request pending for adding Promises to node's core. So if this pull request lands, instead of doing const { readFile } = require('fs')
readFile('blah.txt', (err, data) => {
...
}) You'll be able to do const { readFile } = require('fs').promise
readFile('blah.txt').then(data => {
...
}) They aren't getting rid of the callback API though, so if you want to use promises, you'll have to specify that const { readFile } = require('fs').promise into const { readFile } = require('fs/promise') Either way, I'm really hoping the pull request gets through. |
And for now, there's const { readFile } = require('fs-promise') |
@bluejellybean any progress with this issue? |
Is there a way to not have to type 'return new Promise(( resolve, reject ) => {' every single function?
I almost want to get rid of all callbacks from javascript hah!
The text was updated successfully, but these errors were encountered: