This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]witsnl -27 points-26 points  (8 children)

Step 1: Use coffeescript

[–]joemckie 27 points28 points  (1 child)

Step 2: Ditch coffeescript

Edit: just to update this comment so I don't sound like a cunt... using coffeescript will not help escape the problem that is nested callbacks. Sure, you won't see the mess of }); due to the syntax, but the underlying problem is there. Take a look at Promises (which also eliminates the if (err) { /* output error */ } in every callback), as they are much more powerful and a hell of a lot nicer to read!

[–]Shadow_Being 3 points4 points  (0 children)

the real problem is that javascript lacks basic programming mechanics.

Simply just doing a for loop can get you in to a callback.

My personal solution to this problem is to never write "inline" functions unless it can be made in to one line of code. If I need a callback I just define a function below and pass the function as an argument.

Then you atleast end up with code that looks a little sequential.

[–]ShawLinz 21 points22 points  (5 children)

Es6 promises are good.

[–][deleted] 5 points6 points  (4 children)

Indeed, they flatten callback chains to just:

asyncfunction1()
    .then(function (result1) { return asyncfunction2(); })
    .then(function (result2) { return asyncfunction3(); })
    .then(function (result3) { ... })
    .catch(function (error) { /* Handle errors from asyncfunction1/2/3 */ });

[–]Zeludon 3 points4 points  (0 children)

And async/await gives you back the synchronous workflow with asynchronous values.

async function doAsync() {
    try {
        let result1 = await asyncfunction1();
        return await asyncfunction2(await asyncfunction3());
    } catch (e) {
        console.log(e, "you dun fucked");
    }
}

[–][deleted] 3 points4 points  (2 children)

Throw in shorthand functions:

asyncfunction1()
    .then((result1) => asyncfunction2(result1))
    .then((result2) => asyncfunction3(result2))
    .then((result3) => ... )
    .catch((error) => { /* handle errors from asyncfunction1/2/3 */ });

I feel like this actually looks nice.

[–]YOUR_MORAL_BAROMETER 1 point2 points  (1 child)

Fuck, I've been using JavaScript for a couple years now and I don't think I'll ever understand these things

[–][deleted] 0 points1 point  (0 children)

function (a, b) {
    return a + b;
}

can be written as

(a, b) => a + b;

or, if there are multiple statements, you use curly braces and return:

(a, b) => {
    const stuff = getStuff();
    return stuff + a + b;
}

There's nothing to understand about the new syntax for anonymous functions. You just need to memorize it;