Skip to content

Instantly share code, notes, and snippets.

@ItalyPaleAle
Last active October 7, 2020 03:36
Show Gist options
  • Select an option

  • Save ItalyPaleAle/2caaf2c35f449d9c48deea747f9ce264 to your computer and use it in GitHub Desktop.

Select an option

Save ItalyPaleAle/2caaf2c35f449d9c48deea747f9ce264 to your computer and use it in GitHub Desktop.

Revisions

  1. ItalyPaleAle revised this gist Oct 7, 2020. No changes.
  2. ItalyPaleAle created this gist Oct 7, 2020.
    42 changes: 42 additions & 0 deletions js-promise-with-errors-from-wasm.go
    Original 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)
    })
    }