I have a situation where I want to catch error occurs in the promise first and also return that error to the consumers of the promise. The type of error
is Js.Promise.error
but reject requires an exn
. I know I can use the shady %identity
convertion here. But I wonder is there a better solution ?
Js.Promise.(
resolve(
InternalConfig.apolloClient##mutate({
"mutation": [@bs] gql(mutation##query),
"variables": mutation##variables
})
)
|> then_(value => {
reduce(() => Result(value), ());
resolve();
})
|> catch(error => {
reduce(() => Error(error), ());
reject(error);
})
);
Alright, here is the solution I came up with.
Js.Promise.(
resolve(
InternalConfig.apolloClient##mutate({
"mutation": [@bs] gql(mutation##query),
"variables": mutation##variables
})
)
|> then_(value => {
reduce(() => Ok(value), ());
resolve(Ok(value));
})
|> catch(error => {
reduce(() => Error(error), ());
resolve(Error(error));
})
);
The consumer will be able to do this:
Js.Promise.(
mutate(mutation)
|> then_(result => {
let _ =
Js.Result.(
switch result {
| Ok(_) => setSubmitting(false)
| Error(err) => Js.log(err)
}
);
resolve();
})
);
Pretty nice