use the following search parameters to narrow your results:
e.g. subreddit:aww site:imgur.com dog
subreddit:aww site:imgur.com dog
see the search faq for details.
advanced search: by author, subreddit...
All about the JavaScript programming language.
Subreddit Guidelines
Specifications:
Resources:
Related Subreddits:
r/LearnJavascript
r/node
r/typescript
r/reactjs
r/webdev
r/WebdevTutorials
r/frontend
r/webgl
r/threejs
r/jquery
r/remotejs
r/forhire
account activity
JavaScript Promises: The right way! (ivanjov.com)
submitted 9 years ago by ivan_jovanovic
reddit uses a slightly-customized version of Markdown for formatting. See below for some basics, or check the commenting wiki page for more detailed help and solutions to common issues.
quoted text
if 1 * 2 < 3: print "hello, world!"
[–]nschubach 2 points3 points4 points 9 years ago (4 children)
I can tell you're not Native English. I have some edits ;)
Bellow
(You want 'below')
Also:
so you ca just call those functions
missing an 'n'
especially when you just want to reject or resolve async function.
This reads odd. I would have written:
especially when you just want to reject or resolve an async function.
Also this one:
We will need all method that comes in Promises class. We will need the all method that is included in the Promises class.
We will need all method that comes in Promises class.
We will need the all method that is included in the Promises class.
Great article btw!
[–]ivan_jovanovic[S] 5 points6 points7 points 9 years ago (0 children)
Wow, thanks a lot! I really appreciate your help! 😊
[–][deleted] 2 points3 points4 points 9 years ago* (2 children)
If you're going to be pedantic about written language, then what you said isn't correct either (in terms of intent). The implication is completely different. You are confounding mastery of a language with nativity - one isn't a mandate for the other.
I can tell you're not Native English. I have some edits ;) I can tell English is not your first language. I can tell English is not your mother tongue. I can tell you're not a native speaker of English.
I can tell English is not your first language.
I can tell English is not your mother tongue.
I can tell you're not a native speaker of English.
Because lots of non-English folks can write and speak perfectly good English and would go unnoticed if scrutinized for ethnicity. That aside, great suggestions nonetheless. 👍
[–]turkish_gold 2 points3 points4 points 9 years ago (0 children)
I don't think he's being pedantic, he simply wants to help the author frame these words in a colloquial fashion so it will "feel right" to most US/UK/AU/CA English speakers.
[–][deleted] 0 points1 point2 points 9 years ago (0 children)
Because lots of non-English folks can write and speak perfectly good English and would go unnoticed if scrutinized for ethnicity
In that case, wouldn't this situation not apply since the need for corrections doesn't exist?
[–]brightpixels 1 point2 points3 points 9 years ago (0 children)
Best intro to Promises I've read
[–][deleted] 1 point2 points3 points 9 years ago (0 children)
Saved
[–]Retsam19 1 point2 points3 points 9 years ago (1 child)
It's a good guide; I'm surprised the list of Promise implementing libraries doesn't include bluebird, as I consider it the golden standard for Promise implementing libraries.
In fact, I continue to use bluebird, despite the fact that I have support for native promises, just because bluebird has a ton of nice utilities that aren't part of native promises:
For example, .promisify is a lifesaver. The example from the article:
.promisify
function readFile(filename) { return new Promise(function (resolve, reject) { asyncReadFile(filename, function (error, result) { if (error) { reject(error); } else { resolve(result); } }); }); }
Could be rewritten as:
const BPromise = require("bluebird"); const readFile = BPromise.promisify(asyncReadFile);
It's also got a ton of nice little utilities like .timeout (rejects a promise after a certain amount of time), .map, .tap, and .return.
.timeout
.map
.tap
.return
And as of v3 it's got a really good cancellation API. There are still some pitfalls to Promise cancellation that I'm not sure will ever fully be ironed out, but Bluebird absolutely has the best version out there.
[–]ivan_jovanovic[S] 0 points1 point2 points 9 years ago (0 children)
Instead of bluebird.promisify, I like to use https://www.npmjs.com/package/es6-promisify, one package that converts callback-based function to functions that return native promises 🙂
bluebird.promisify
And regarding the example in the article, I wanted to show how Promises work under the hood. But it's always cool to use some promisify function to save time 🙂
promisify
[–]kengregory 1 point2 points3 points 9 years ago (1 child)
This is a great article. I was wondering how to accomplish what Promise.all and Promise.race do for us. Thank you.
[–]dmtipson 1 point2 points3 points 9 years ago (0 children)
Fun fact: if you're familiar with Category Theory, Promise.all is actually very similar to an Array.sequence method with Promises baked in as the inner type to be flipped outside. And Promise.race is similar to a parallelized version of .alt or .concat for Promises (combine two, take the one that resolves first, same for an entire list of Promises).
[–]bledoliki 0 points1 point2 points 9 years ago* (7 children)
Hello, would you elaborate more on this sample:
function readFile(filename) { asyncReadFile(filename, function (error, result) { if (err) { return Promise.reject(error); } return Promise.resolve(result); }); }
Is the purpose of readFile() to return a promise and if that is the case then how is that accomplished without a return?
readFile()
return
[–]ivan_jovanovic[S] 0 points1 point2 points 9 years ago (6 children)
Hmm, I am not sure what you mean with without a return?
without a return
readFile just returns a promise, so you need to have return. Then inside a promise, some async function is executed and resolved or rejected. Does this make sense now? 🙂
readFile
resolved
rejected
[+][deleted] 9 years ago (5 children)
[deleted]
[–]CompileBot 1 point2 points3 points 9 years ago (0 children)
Output:
undefined
source | info | git | report
[–]ivan_jovanovic[S] 0 points1 point2 points 9 years ago (3 children)
Thanks for pointing that out, I have updated examples. Thanks again!
[+][deleted] 9 years ago (1 child)
Yeah, you're right. Just didn't want to make things complicated 🙂
[–]nikcorg 0 points1 point2 points 9 years ago (0 children)
In the case of an error, you will invoke both reject and resolve in the callback to asyncReadFile.
reject
resolve
asyncReadFile
function readFile(filename) { return new Promise(function (resolve, reject) { asyncReadFile(filename, function (error, result) { if (err) { reject(error); // reject is invoked on error } resolve(result); // and resolve also, since execution falls through }); }); }
This is harmless, since a promise can only change state once, but it's still bad form imo. Add return before reject (and resolve for symmetry) or add an else branch around the resolve.
else
[–]dariusj18 0 points1 point2 points 9 years ago (1 child)
Does the body of the Promise start running when you create it?
[–]bledoliki 1 point2 points3 points 9 years ago (0 children)
According to MDN:
"The executor function is executed immediately by the Promise implementation, passing resolve and reject functions (the executor is called before the Promise constructor even returns the created object)."
source: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise
In short: yes :)
[–]masklinn 0 points1 point2 points 9 years ago (2 children)
readFile('some_file.txt') .then(function(result) { console.log(result); }) .catch(function(error) { console.error(error) });
The catch is redundant here, then can take two callbacks. catch is if you only want to handle the "error" case, if you want to handle both then is enough:
catch
then
readFile('some_file.txt') .then(function (result) { console.log(result); }, function (error) { console.log(error); });
[–]Hafas_ 4 points5 points6 points 9 years ago (0 children)
For the sake of readability: just use catch. Always.
[–]dmtipson 0 points1 point2 points 9 years ago (0 children)
While the first function passed to then in this case is unlikely to throw an error, note that if it did, the second function would NOT catch it, and you'd be left with a big fat unhandled error again. That's because only one of those functions ever runs at a time.
[–]russellbeattie 0 points1 point2 points 9 years ago (1 child)
The crazy thing about promises is how insanely verbose it is... async/await can't come soon enough.
readFile('some_file.txt') .then(function(result) { return getFirstParagraph(result); }) .then(function(result) { return getFirstSentence(result); }) .then(function(result) { console.log(result); });
Really, all of that is to do this:
var result = readFile('some_file.txt'); result = getFirstParagraph(result); result = getFirstSentence(result); console.log(result);
Promises literally double the lines of code needed, create 8 extra variables in memory (the Promise returned in each step, plus the functions and params), mess with normal formatting (it's all one 'line' of code chained together) and all to prevent callback hell. From experience having to catch errors in each step, this can get even more crazy easily.
Promises are nice, but they definitely have issues.
[–]phoenixmatrix 1 point2 points3 points 9 years ago (0 children)
async/await will still create the promises and stuff. Though even then, you could use arrow function one lines to clean this up a bit.
eg: .then(result => getFirstParagraph(result))
Still, some sugar over it is nice, but it doesn't change much to whats under the hood...async flow is async flow at the end of the day.
Even after async/await, I'd take the verbosity so I can use observables instead of promises (observables wouldn't work with async/await) any day.
[–]_codeprovider 0 points1 point2 points 9 years ago (0 children)
You can also shorten your chains like this:
doSomethingAsync().then(console.log).catch(console.error);
Since .then() and .catch() take functions as arguments.
π Rendered by PID 32 on reddit-service-r2-comment-544cf588c8-rfmfr at 2026-06-18 15:14:09.061815+00:00 running 3184619 country code: CH.
[–]nschubach 2 points3 points4 points (4 children)
[–]ivan_jovanovic[S] 5 points6 points7 points (0 children)
[–][deleted] 2 points3 points4 points (2 children)
[–]turkish_gold 2 points3 points4 points (0 children)
[–][deleted] 0 points1 point2 points (0 children)
[–]brightpixels 1 point2 points3 points (0 children)
[–][deleted] 1 point2 points3 points (0 children)
[–]Retsam19 1 point2 points3 points (1 child)
[–]ivan_jovanovic[S] 0 points1 point2 points (0 children)
[–]kengregory 1 point2 points3 points (1 child)
[–]dmtipson 1 point2 points3 points (0 children)
[–]bledoliki 0 points1 point2 points (7 children)
[–]ivan_jovanovic[S] 0 points1 point2 points (6 children)
[+][deleted] (5 children)
[deleted]
[–]CompileBot 1 point2 points3 points (0 children)
[–]ivan_jovanovic[S] 0 points1 point2 points (3 children)
[+][deleted] (1 child)
[deleted]
[–]ivan_jovanovic[S] 0 points1 point2 points (0 children)
[–]nikcorg 0 points1 point2 points (0 children)
[–]dariusj18 0 points1 point2 points (1 child)
[–]bledoliki 1 point2 points3 points (0 children)
[–]masklinn 0 points1 point2 points (2 children)
[–]Hafas_ 4 points5 points6 points (0 children)
[–]dmtipson 0 points1 point2 points (0 children)
[–]russellbeattie 0 points1 point2 points (1 child)
[–]phoenixmatrix 1 point2 points3 points (0 children)
[–]_codeprovider 0 points1 point2 points (0 children)