neverthrow icon indicating copy to clipboard operation
neverthrow copied to clipboard

[question] how to combine the sync and async api?

Open unknown1337 opened this issue 2 years ago • 3 comments

I have a parent function that returns a resultasync as it executes at least one async child function. the two child functions to chain return a Result and a ResultAsync respectively.

question, how can I combine Result and ResultAsync ?

Thanks!

function syncValidation():Result<string,Error>{.... perform e.g. input validation}
function asyncFetch():ResultAsync<string,Error>{.... perform e.g. network call}

function parent(id:string):ResultAsync<string,Error>{
  return syncValidation().andThen(id=>asyncFetch(id))   // <---- this line
}

Do i need to create helper functions myselve to wrap the syncValidation function or is there some smarter way?

function wrapResult<T, E>(result: Result<T, E>): ResultAsync<T, E> {
  if (result.isOk()) return okAsync(result.value);
  else return errAsync(result.error);
}

unknown1337 avatar Jul 13 '23 13:07 unknown1337

Hello @unknown1337

you can use https://github.com/supermacro/neverthrow#resultasyncandthen-method

cheers

paduc avatar Jul 13 '23 15:07 paduc

thanks, solved, completely missed that!

unknown1337 avatar Jul 14 '23 07:07 unknown1337

close

unknown1337 avatar Jul 14 '23 07:07 unknown1337