Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

how to support timeout ? #21

Closed
miaozilong opened this issue Jun 30, 2020 · 4 comments
Closed

how to support timeout ? #21

miaozilong opened this issue Jun 30, 2020 · 4 comments

Comments

@miaozilong
Copy link

your example is get ip from the remote
but if my network is poor that it'll last long time
i wanna to reject after 3 second if the ip does't get

@miaozilong
Copy link
Author

i solved the problem !

package main

import (
	"errors"
	"fmt"
	"github.com/chebyrash/promise"
	"io/ioutil"
	"net/http"
	"time"
)

func main() {
	var requestPromise = promise.New(func(resolve func(interface{}), reject func(error)) {
		go func() {
			time.Sleep(2 * time.Second)
			reject(errors.New("time out error"))
		}()
		resp, err := http.Get("https://httpbin.org/ip")
		defer resp.Body.Close()
		if err != nil {
			reject(err)
			return
		}
		body, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			reject(err)
			return
		}
		resolve(body)
	})

	// Parse JSON body in async manner
	parsed, err := requestPromise.Await()

	if err != nil {
		fmt.Printf("Error: %s\n", err.Error())
		return
	}
	ip := fmt.Sprintf("%s", parsed)

	fmt.Println(ip)
}

@chebyrash
Copy link
Owner

chebyrash commented Jun 30, 2020

Hi,

Have a look at https://golang.org/pkg/net/http/#Client
The easiest way is to use is the Timeout field of http.Client

c := &http.Client{
    Timeout: 15 * time.Second,
}
resp, err := c.Get("https://httpbin.org/ip")

Or you can use

go func() {
    time.Sleep(2 * time.Second)
    reject(errors.New("time out error"))
}()

@miaozilong
Copy link
Author

i want to use
promise.Wait(2*time.Second)
how to solve it it's more useful

@miaozilong
Copy link
Author

parsed, err := requestPromise.Await( 2 * time.Second )

how to use like this?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants