Last active
October 7, 2020 03:36
-
-
Save ItalyPaleAle/2caaf2c35f449d9c48deea747f9ce264 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Copyright (C) 2020 Alessandro Segala (ItalyPaleAle) | |
// License: MIT | |
// MyGoFunc returns a Promise that fails with an exception about 50% of times | |
func MyGoFunc() js.Func { | |
return js.FuncOf(func(this js.Value, args []js.Value) interface{} { | |
// Handler for the Promise | |
handler := js.FuncOf(func(this js.Value, args []js.Value) interface{} { | |
resolve := args[0] | |
reject := args[1] | |
// Run this code asynchronously | |
go func() { | |
// Cause a failure 50% of times | |
if rand.Int()%2 == 0 { | |
// Invoke the resolve function passing a plain JS object/dictionary | |
resolve.Invoke(map[string]interface{}{ | |
"message": "Hooray, it worked!", | |
"error": nil, | |
}) | |
} else { | |
// Assume this were a Go error object | |
err := errors.New("Nope, it failed") | |
// Create a JS Error object and pass it to the reject function | |
// The constructor for Error accepts a string, | |
// so we need to get the error message as string from "err" | |
errorConstructor := js.Global().Get("Error") | |
errorObject := errorConstructor.New(err.Error()) | |
reject.Invoke(errorObject) | |
} | |
}() | |
// The handler of a Promise doesn't return any value | |
return nil | |
}) | |
// Create and return the Promise object | |
promiseConstructor := js.Global().Get("Promise") | |
return promiseConstructor.New(handler) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment