4

JavaScript return await

 2 years ago
source link: https://blog.mathieu-leplatre.info/javascript-return-await.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

JavaScript return await

JavaScript return await

Thu 07 November 2019

A very short article about one of the recent bugs I carelessly designed :)

I wrote the code below and had certain expectations: no matter what happens, catch the error and return a fallback value.

async function dl(uri) {
  try {
    const resp = await fetch(uri);
    const data = await resp.json();
    return data;
  } catch (e) {
    console.warn(e);
    return {success: false};
  }
}

Since I find it a bit verbose, I rewrote it this way:

async function dl(uri) {
  try {
    const resp = await fetch(uri);
    return await resp.json();
  } catch (e) {
    console.warn(e);
    return {success: false};
  }
}

Before ESLint could complain about no-return-await), I removed this ugly redundant use of await on a return value. The function returns a promise after all!

async function dl(uri) {
  try {
    const resp = await fetch(uri);
    return resp.json();
  } catch (e) {
    console.warn(e);
    return {success: false};
  }
}

Nice and short!

Maybe you did, but at the time I didn't notice that I had just changed the behaviour of the function. Now, when a JSON parsing error occurs, it will be thrown at the caller instead of returning the fallback value! That's not what I intended and now the code can be misinterpreted :)

ESLint is smart enough to take the try {} catch () {} into account, my inner voice wasn't.

Conclusion: use your tests to specify the behaviour of your code!

#javascript - Posted in the Dev category

© Copyright 2020 by Mathieu Leplatre. mnmlist Theme

Content licensed under the Creative Commons attribution-noncommercial-sharealike License.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK