6
DJTM
4y

Small rant because I’m new here, but…I hate async functions in JavaScript.
Especially when dealing with an API.

Comments
  • 3
    Also I think I should have looked more into what this platform is before posting this xD
  • 1
    Yep. Do go on though, what is it precisely you hate about async functions?
  • 1
    Maybe inconsistency? Even after years still some things are just cumbersome with async/await (or you sometimes have to resort for callbacks or explicit Promises)

    Deno looks promising with its top level async/await

    I think that new version of Node also supports it now, or was it only in REPL?
  • 3
    @stefanjarina exactly this.
    It can just get frustrating at times
  • 0
    @DJTM
    Examples?

    I use Observable as my primary async construct, so I have no dog in the fight per se.
  • 2
    I hate working with an API that offers async/await/promise structure and thereby makes it impossible to use normal JavaScript structure for data processing.
    Example Discord.JS
  • 0
    @SortOfTested @SortOfTested

    Using node-fetch

    The async function;

    async function getPlayerId(usernameInput){//function to fetch player id from name
    const api_response = await fetch('http://example.com/api/players/...);
    const data = await api_response.json();
    //message.channel.send(data.players[0].playerId);
    return(data.players[0].playerId);
    }

    The call to function;

    let playerId = getPlayerId(q);
    playerId.then(function(playerId) {
    //code that uses API here
    }
  • 2
    @Ranchu this is exactly the case I have, discord.js and APIs
  • 2
    @DJTM
    Yeah, that's kind of fugly. There's a lot of pick apart there. This is how it looks in my world:

    const getPlayerId$ = (username: string) => from(
    fetch(`http://example.com/api/players/...}`)
    ).pipe(
    map(response => response.json()),
    map(({players}) => players && players[0].playerId)
    );

    // usage
    function bindPlayer(player: Player, username: string){
    combineLatest(of(player), getPlayerId$(username))
    .pipe(
    map(([player, playerId]) => //use player id here, return player),
    ).subscribe(
    //(boundPlayer: player) => void here
    );
    }
  • 0
    @SortOfTested hmm, Angular world, or plain RxJs?
  • 0
    @stefanjarina
    That's rxjs.

    Angular would use HttpClient and not need to encapsulate the promise in a stream.
  • 0
    @SortOfTested it never occured to me I could use rxjs outside of angular :-D need to try it out in some project. Thanks for an idea :-)
  • 0
    @DJTM I kinda expected you to have these problems.
    I don't know any other JavaScript based API that fucks with async stuff as much as DJS
  • 0
    @DJTM why not define the function consumes the playerID earlier?
Add Comment