2014-04-25 77 views
1

这是一个问题。当我运行这些代码:请求正在运行时等待

String responseText = null; 

HttpRequest.getString(url).then((resp) { 
    responseText = resp; 
    print(responseText); 
    }); 
print(responseText); 

在控制台:

{"meta":{"code":200},"data":{"username":"kevin","bio":"CEO \u0026 Co-founder of Instagram","website":"","profile_picture":"http:\/\/images.ak.instagram.com\/profiles\/profile_3_75sq_1325536697.jpg","full_name":"Kevin Systrom","counts":{"media":1349,"followed_by":1110365,"follows":555},"id":"3"}} 
null 

它异步运行。有同步方法的JAVA方式吗?请求完成后,这将会等待吗? 我发现只有一个取巧的办法来做到这一点,其滑稽 - 等待3秒钟:

handleTimeout() { 
    print(responseText); 
} 
const TIMEOUT = const Duration(seconds: 3); 
new Timer(TIMEOUT, handleTimeout); 

当然,它与虫子的作品。那么有什么建议?

MattB方式工作做好:

var req = new HttpRequest(); 
    req.onLoad.listen((e) { 
    responseText = req.responseText; 
    print(responseText); 
    }); 
    req.open('GET', url, async: false); 
    req.send(); 

回答

3

首先,我假设你正在使用这个作为客户端脚本,而不是服务器端。使用HttpRequest.getString将严格返回Future(异步方法)。

如果你绝对必须有一个同步的请求,你可以构造一个新的HttpRequest对象,并调用open方法传递命名参数:async: false

var req = new HttpRequest(); 
req.onLoad.listen((e) => print(req.responseText)); 
req.open('GET', url, async: false); 
req.send(); 

但是,强烈建议您使用访问异步方法网络资源作为上述的同步调用将导致脚本阻塞,并可能使其显示为您的页面/脚本在恶劣的网络连接上停止响应。

+0

是的,客户端。仍然打印null – raiym

+0

您的代码根据文档必须工作,但我不知道为什么它为空 – raiym

+0

https://api.dartlang.org/apidocs/channels/stable/dartdoc-viewer/dart-dom-html.HttpRequest#id_open ,异步 – raiym