0

Here is the code:

function getList() {
    return functionList()
        .then((list) => functionDetails())
        .catch((err) => console.log(err));
}

how to convert it to async/await?

steven
  • 11
  • 3
  • https://umaar.com/dev-tips/182-typescript-async-await/ – tomleb Feb 25 '22 at 13:00
  • https://javascript.info/async-await best examples – Anshuk Sharma Feb 25 '22 at 13:02
  • Are you sure you are you don't want to use the result of `functionList()`? – derpirscher Feb 25 '22 at 13:02
  • Please [edit] your question to show what research you've done into the issue and any attempts you've made to solve the problem yourself. – Heretic Monkey Feb 25 '22 at 13:11
  • This will work as is with `async / await`, although I would remove the `catch` if this is not a top level call, otherwise the callee is not going to know there was an error as your swallowing it up. And what has the above code got to do with React? – Keith Feb 25 '22 at 13:14
  • There are [many, many questions about converting promise/then based code to async/await](https://stackoverflow.com/search?q=convert+promise+to+async+await). Please demonstrate what make this one different. – Heretic Monkey Feb 25 '22 at 13:19
  • 1
    Does this answer your question? [Converting promises to async/await - Javascript](https://stackoverflow.com/questions/55272701/converting-promises-to-async-await-javascript) – Heretic Monkey Feb 25 '22 at 13:21

1 Answers1

0

You can wrap the call to the awaited function in a try-catch to handle the error, and then run your .then code in the finally block

async function getList() {
    try {
        const result = await functionList();
        return ((result) => functionDetails()());
    } catch(e) {
        console.log(e);
    }
}
Tom
  • 1,158
  • 6
  • 19
  • Nope, this has a different semantics. It calls `functionDetails` in any case, whereas OP calls it only when `functionList` didn't reject ... – derpirscher Feb 25 '22 at 13:03
  • Will the return inside the catch not prevent the finally block from running if there's an error? – Tom Feb 25 '22 at 13:05
  • No, the `finally` is executed no matter what you do in the `try` or the `catch` block. That's the whole purpose of `finally` – derpirscher Feb 25 '22 at 13:06
  • So if we raise the call to functionDetails inside the try block that seems to work correctly – Tom Feb 25 '22 at 13:10