gavel-gateway-js: Working with Promises

What are Promises

Promises represent asynchronous actions that are going to finish processing in the future, or have already finished processing. Whenever the programm encounters a promise, it will finish it's current routine and then process the Promise. This behaviour is called run-to-completion.

Dealing with Promises

There are a couple ways to deal with promises in Javascript, the most common two are are shown below. Here the fetchPlayer() function returns a promise which will resolve to a Player.

  1. Pause execution until the promise finishes.

    console.log(1);
    const player = await api.fetchPlayer("Salted").catch(function (error) {
    console.log(error);
    });
    console.log(player.name);
    console.log(2);

    // Output:
    // 1
    // Salted
    // 2

    This approach will pause the currently executing function until the promise has finished processing. The result is then assigned to the variable player. Other code may be executed while this function awaits the result.

  2. Continue in .then() on promise finish

    console.log(1);
    api.fetchPlayer("Salted")
    .then(player => console.log(player.name))
    .catch(function (error) {
    console.log(error);
    });
    console.log(2);

    // Output:
    // 1
    // 2
    // Salted

    This approach will not pause execution, it will continue execution to the end of the function and only after that start fetching the data. Once the data has been fetched, the function passed to the .then() function will be executed.

Catching Errors

Promises may throw exceptions. Especially APIs using the internet are prone to errors in case of timeouts etc. It is therefore usually necessary to attach a .catch() block to the promise. A catch block acts just like a try { ... } catch (error) { ... } statement, though the latter will not work unless you use await. Catch blocks pass the error as a single parameter to the function inside of them.

Generated using TypeDoc