gpt4 book ai didi

dart - 等待请求正在运行

转载 作者:行者123 更新时间:2023-12-03 03:19:01 25 4
gpt4 key购买 nike

这是个问题。当我运行这些代码时:

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方式与同步方式吗?请求完成后将等待吗?
我发现只有一种棘手的方法可以做到,而且很有趣-等待三秒钟:

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();

最佳答案

首先,我假设您将其用作客户端脚本而不是服务器端。使用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();

但是,强烈建议您使用异步方法来访问网络资源,因为如上所述的同步调用将导致脚本阻塞,并有可能使其看起来好像您的页面/脚本已停止响应不良的网络连接。

关于dart - 等待请求正在运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23298659/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com