question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

How to avoid "callback-hell" type of syntax?

See original GitHub issue

I am looking into this library. However I can’t seem to understand how I would avoid nesting .maps inside each other.

For example, I would do something like:

asyncOperation1.map(success1 => {
  console.log("cool: ", success1);
  asyncOperation2.map(success2 => {
    console.log("cool: ", success2);
    asyncOperation3.map(success3 => {
      ...
    }).mapErr(err => {
      console.log("uh oh", err);
    });
  }).mapErr(err => {
    console.log("uh oh", err);
  });
.mapErr(err => {
  console.log("uh oh", err);
});

I feel like I must be missing something but I haven’t seen any examples addressing this case, of multiple async operations that depend on previous results. Any links to examples or suggestions for this?

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:5 (3 by maintainers)

github_iconTop GitHub Comments

2reactions
paduccommented, Feb 18, 2021

@rhlsthrm I believe you tend to unwrap the result too early. A more idiomatic approach is to keep the result wrapped for as long as possible and use .andThen to chain each successive operation.

const res = doSomething(); // res is ResultAsync<T1,E1>
const res2 = res.andThen(doSomethingElse) // res2 is ResultAsync<T2, E1 | E2>
// ... later on, call match

// or more simply
const res = doSomething().andThen(doSomethingElse)

It really behaves like a Promise in that, you can chose to await right away or chain it with .then and keep it as a promise. The difference is that the error case is typed and it’s a lot harder to forget to handle it.

A good indicator that you are using neverthrow correctly is that you use andThen way more often than isOk/isError/match.

1reaction
paduccommented, Feb 18, 2021

Hello @rhlsthrm !

When chaining multiple operations, you would do something similar to a chain of Promises.

const result = asyncOperation1.andThen(asyncOperation2).andThen(asyncOperation3)

The error case can be handled at the very end of the chain using .match or isErr() and .error.

const result = await asyncOperation1.andThen(asyncOperation2).andThen(asyncOperation3)
if(result.isErr()){
  console.error(result.error)
}
else{
  console.log('Success', result.value)
}

// or
await asyncOperation1.andThen(asyncOperation2).match((value) => console.log('success', value), (error) => console.error(error))

I personally make web apps, and use ResultAsync everywhere in my app but only use .match in my controllers, where I unwrap the final ResultAsync and decide what to do in the different error cases (because there are several error types) and the success case.

Here is a live production example of a controller unwrapping the value/error cases.

Read more comments on GitHub >

github_iconTop Results From Across the Web

How to avoid callback hell in Node.js ? - GeeksforGeeks
We can avoid the callback hell with the help of Promises. Promises in javascript are a way to handle asynchronous operations in Node.js....
Read more >
Avoiding Callback Hell in Node.js - Stack Abuse
One of the best ways to reduce code clutter is by maintaining better separation of code. If you declare a callback function beforehand...
Read more >
Callback Hell
Callback hell is caused by poor coding practices. Luckily writing better code isn't that hard! You only need to follow three rules: 1....
Read more >
Callback Hell – BMC Software | Blogs
It is a slang term used to describe and unwieldy number of nested “if” statements or functions. If you are not expecting your...
Read more >
Callback hell: How to avoid it using promises, bluebird and ES7
This article will solve the problem of asynchronous control flow in JavaScript and will prevent you from falling into the callback hell.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found