Last active
June 4, 2023 05:30
-
-
Save cowboy/79fddf22d1a692468556 to your computer and use it in GitHub Desktop.
JavaScript: why do we write async code the way we do?
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
// 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
I think this is the best way...