promise

package module
v0.0.0-...-fbfa07d Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 3, 2018 License: MIT Imports: 0 Imported by: 1

README

ES6 Promsie in Go

Write functions like ES6 Promise.

promise.go is simple, which is less then 100 lines. Please read it.

Example

API likes axios.js to do http request.

ajax/ajax.go

package ajax

import (
	"net/http"

	"github.com/Asphaltt/promise"
)

// Get wraps http.Get as promise
func Get(url string) *promise.Promise {
	return promise.Init(http.Get(url))
}

examples/axios/main.go

package main

import (
	"fmt"
	"net/http"

	"github.com/Asphaltt/promise/axios"
)

func main() {
	axios.Get("https://www.bing.com").Then(func(v interface{}) (interface{}, error) {
		resp := v.(*http.Response)
		fmt.Println(resp.Status)
		return nil, nil
	}).Catch(func(e error) {
		fmt.Println(e)
	})
}

Another way

Another way to do axios with promise.

func main() {
    promise.Init(http.Get("https://www.bing.com")).Register(func(v interface{}) (interface{}, error) {
        resp := v.(*http.Response)
        fmt.Println(resp.Status)
        return nil, nil
    }).Catcher(func(e error) {
        fmt.Println(e)
    }).Done()
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Catcher

type Catcher func(error)

Catcher catches error

type Func

type Func func(v interface{}) (ret interface{}, err error)

Func is the handler of promise. The argument v is for passing all arguments.

type Promise

type Promise struct {
	// contains filtered or unexported fields
}

Promise executes its handlers and catches error

func Init

func Init(v interface{}, e error) *Promise

Init creates a promise with initiated value and error

func New

func New() *Promise

New creates a promise

func (*Promise) Catch

func (p *Promise) Catch(c Catcher)

Catch catches error for promise

func (*Promise) Catcher

func (p *Promise) Catcher(c Catcher) *Promise

Catcher sets the error handler for promise

func (*Promise) Done

func (p *Promise) Done() error

Done executes all registered handlers of promise and catch the error

func (*Promise) DoneAsync

func (p *Promise) DoneAsync()

DoneAsync runs Done in a goroutine

func (*Promise) Register

func (p *Promise) Register(fn Func) *Promise

Register registers a handler to promise

func (*Promise) Result

func (p *Promise) Result() (interface{}, error)

Result gets the result of promise

func (*Promise) Then

func (p *Promise) Then(fn Func) *Promise

Then does the next step of callback fn to do

Directories

Path Synopsis
examples
axios command

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL