Created
October 7, 2020 03:38
-
-
Save ItalyPaleAle/6011932149959d875a3131b5ad396022 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 resolves after 3 seconds with a message | |
func MyGoFunc() js.Func { | |
return js.FuncOf(func(this js.Value, args []js.Value) interface{} { | |
// Handler for the Promise: this is a JS function | |
// It receives two arguments, which are JS functions themselves: resolve and reject | |
handler := js.FuncOf(func(this js.Value, args []js.Value) interface{} { | |
resolve := args[0] | |
// Commented out because this Promise never fails | |
//reject := args[1] | |
// Now that we have a way to return the response to JS, spawn a goroutine | |
// This way, we don't block the event loop and avoid a deadlock | |
go func() { | |
// Block the goroutine for 3 seconds | |
time.Sleep(3 * time.Second) | |
// Resolve the Promise, passing anything back to JavaScript | |
// This is done by invoking the "resolve" function passed to the handler | |
resolve.Invoke("Trentatré Trentini entrarono a Trento, tutti e trentatré trotterellando") | |
}() | |
// 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