Skip to content

Instantly share code, notes, and snippets.

@manjeettahkur
Forked from cowboy/why.js
Created November 21, 2015 10:46
Show Gist options
  • Save manjeettahkur/9901bb854c00946ec66b to your computer and use it in GitHub Desktop.
Save manjeettahkur/9901bb854c00946ec66b to your computer and use it in GitHub Desktop.
JavaScript: why do we write async code the way we do?
// This is an UBER simplified example, but I hope you get the idea...
function thisIsHowWeWriteSyncCode(arg) {
var foo = doSomething(arg);
var bar = doSomethingElse(foo);
var baz = doSomethingWith("test", bar, 123);
return doLastThing(baz);
}
function soThisSeemsSensibleForAsyncCode(arg) {
var foo = doSomethingAsync(arg);
var bar = foo.then(doSomethingElseAsync);
var baz = bar.then(function(result) {
return doSomethingAsyncWith("test", result, 123);
});
return baz.then(doLastAsyncThing);
}
function soWhyDoWeWriteAllOurAsyncCodeLikeThis(arg) {
return doSomethingAsync(arg).then(doSomethingElseAsync).then(function(result) {
return doSomethingAsyncWith("test", result, 123);
}).then(doLastAsyncThing);
}
function thatsLikeAlwaysWritingSyncCodeLikeThis(arg) {
return doLastThing(doSomethingWith("test", doSomethingElse(doSomething(arg)), 123));
}
function iDontThinkIndentationHelpsEither(arg) {
return doSomethingAsync(arg)
.then(doSomethingElseAsync)
.then(function(result) {
return doSomethingAsyncWith("test", result, 123);
})
.then(doLastAsyncThing);
}
function thatsKindaLikeDoingThis(arg) {
return doLastThing(
doSomethingWith(
"test",
doSomethingElse(
doSomething(arg)
),
123
)
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment