Last active
October 7, 2020 03:36
-
-
Save ItalyPaleAle/2caaf2c35f449d9c48deea747f9ce264 to your computer and use it in GitHub Desktop.
Revisions
-
ItalyPaleAle revised this gist
Oct 7, 2020 . No changes.There are no files selected for viewing
-
ItalyPaleAle created this gist
Oct 7, 2020 .There are no files selected for viewing
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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,42 @@ // 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) }) }