是否可以阻止返回 future 的函数调用?
我在印象中打电话.then()
这样做,但这不是我在输出中看到的。
print("1");
HttpRequest.getString(url).then((json) {
print("2");
});
print("3");
我在输出中看到的是:
1
3
2
getString
方法没有 async
这将允许我await
它和 then
在任何情况下都异步执行。 static Future<String> getString(String url,
{bool withCredentials, void onProgress(ProgressEvent e)}) {
return request(url, withCredentials: withCredentials,
onProgress: onProgress).then((HttpRequest xhr) => xhr.responseText);
}
在第 3 步等待第 2 步完成之前,如何使其阻塞而不放置无限 while 循环(由于 Dart 的单线程性质,它无论如何都不会工作)?
上面的 HttpRequest 加载了一个
config.json
如果对配置中的字段的请求在 config.json
之前完成,则该文件决定了应用程序中的一切工作方式。文件已完成加载,它会导致错误,因此我需要等到文件完成加载,然后才能允许在类的字段上调用 getter 或 getter 需要等待 config.json
的一次性加载文件。更新 ,这就是我在 Günter 建议我使用
Completer
后最终让它工作的方法。 :@Injectable()
class ConfigService {
Completer _api = new Completer();
Completer _version = new Completer();
ConfigService() {
String jsonURI =
"json/config-" + Uri.base.host.replaceAll("\.", "-") + ".json";
HttpRequest.getString(jsonURI).then((json) {
var config = JSON.decode(json);
this._api.complete(config["api"]);
this._version.complete(config["version"]);
});
}
Future<String> get api {
return this._api.future;
}
Future<String> get version {
return this._version.future;
}
}
我在哪里使用
ConfigService
: @override
ngAfterContentInit() async {
var api = await config.api;
var version = await config.version;
print(api);
print(version);
}
现在我获得了类似阻塞的功能,但实际上并没有阻塞。
最佳答案
在异步代码完成之前,无法阻止执行。你能做的就是链条 连续代码,以便在异步代码完成之前不会执行它。
一种链接方式是 then
print("1");
HttpRequest.getString(url) // async call that returns a `Future`
.then((json) { // uses the `Future` to chain `(json) { print("2"); }`
print("2");
});
print("3"); // not chained and therefore executed before the `Future` of `getString()` completes.
异步调用只是为以后执行安排代码。它将被添加到事件队列中,当处理它之前的任务时,它本身将被执行。在安排了异步调用后,将继续同步代码 `print("3")。
在你的情况下
HttpRequest.getString()
安排对您的服务器的调用并注册 (json) { print("2")
作为服务器响应到达时调用的回调。应用程序的进一步执行在响应到达之前不会停止,并且没有办法让它发生。相反发生的是同步代码继续执行( print("3")
)。如果您当前执行的同步代码到达终点,那么下一个计划任务将以相同的方式处理。
then()
调度代码 (json) { print("2"); }
在 getString()
之后执行完全的。等待
async
和 await
只需制作异步代码 看 更像是同步代码,但其他方面完全相同,将在引擎盖下转换为 xxx.then((y) { ... })
.
关于dart - 制作一个 Future block 直到它完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37712910/