Skip to content

Instantly share code, notes, and snippets.

@cowboy
Last active June 4, 2023 05:30
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save cowboy/79fddf22d1a692468556 to your computer and use it in GitHub Desktop.
Save cowboy/79fddf22d1a692468556 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
)
);
}
@skyrpex
Copy link

skyrpex commented Jun 25, 2015

I think this is the best way...

function iDontThinkIndentationHelpsEither(arg) {
  return doSomethingAsync(arg)
    .then(doSomethingElseAsync)
    .then(function(result) {
      return doSomethingAsyncWith("test", result, 123);
    })
    .then(doLastAsyncThing);
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment