Function tauri::api::ipc::format_callback_result
source · pub fn format_callback_result<T: Serialize, E: Serialize>(
result: Result<T, E>,
success_callback: CallbackFn,
error_callback: CallbackFn
) -> Result<String>
Expand description
Formats a Result type to its Promise response.
Useful for Promises handling.
If the Result is_ok()
, the callback will be the success_callback
function name and the argument will be the Ok value.
If the Result is_err()
, the callback will be the error_callback
function name and the argument will be the Err value.
result
the Result to checksuccess_callback
the function name of the Ok callback. Usually theresolve
of the JS Promise.error_callback
the function name of the Err callback. Usually thereject
of the JS Promise.
Note that the callback strings are automatically generated by the invoke
helper.
Examples
use tauri::api::ipc::{CallbackFn, format_callback_result};
let res: Result<u8, &str> = Ok(5);
let cb = format_callback_result(res, CallbackFn(145), CallbackFn(0)).expect("failed to format");
assert!(cb.contains(r#"window["_145"](5)"#));
let res: Result<&str, &str> = Err("error message here");
let cb = format_callback_result(res, CallbackFn(2), CallbackFn(1)).expect("failed to format");
assert!(cb.contains(r#"window["_1"]("error message here")"#));
Examples found in repository?
src/hooks.rs (line 269)
262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
pub fn window_invoke_responder<R: Runtime>(
window: Window<R>,
response: InvokeResponse,
success_callback: CallbackFn,
error_callback: CallbackFn,
) {
let callback_string =
match format_callback_result(response.into_result(), success_callback, error_callback) {
Ok(callback_string) => callback_string,
Err(e) => format_callback(error_callback, &e.to_string())
.expect("unable to serialize response string to json"),
};
let _ = window.eval(&callback_string);
}