我试图通过自己学习Dart,但我来自C,我有点困惑......
我这样做:
import 'dart:io';
import 'dart:async';
import 'dart:convert';
Future <Map> ft_get_data()
{
File data;
data = new File("data.json");
return data.exists().then((value) {
if (!value)
{
print("Data does no exist...\nCreating file...");
data.createSync();
print("Filling it...");
data.openWrite().write('{"index":{"content":"Helllo"}}');
print("Operation finish");
}
return (1);
}).then((value) {
data.readAsString().then((content){
return JSON.decode(content);
}).catchError((e) {
print("error");
return (new Map());
});
});
}
void main()
{
HttpServer.bind('127.0.0.1', 8080).then((server) {
print("Server is lauching... $server");
server.listen((HttpRequest request) {
request.response.statusCode = HttpStatus.ACCEPTED;
ft_get_data().then((data_map) {
if (data_map && data_map.isNotEmpty)
request.response.write(data_map['index']['content']);
else
request.response.write('Not work');
}).whenComplete(request.response.close);
});
}) .catchError((error) {
print("An error : $error.");
});
}
我正在尝试取回新 Map ,正如你猜测的那样,它不起作用,我得到了“不工作”的信息 . 当代码处于同一功能时,它起作用了......
拜托,你能帮帮我吗?
并且,指针系统为C?
void function(int *i)
{
*i = 2;
}
int main()
{
int i = 1;
function(&i);
printf("%d", i);
}
// Output is 2.
谢谢您的帮助 .
最终代码:
import 'dart:io';
import 'dart:async';
import 'dart:convert';
Future<Map> ft_get_data()
{
File data;
data = new File("data.json");
return data.exists()
.then((value) {
if (!value) {
print("Data does no exist...\nCreating file...");
data.createSync();
print("Filling it...");
data.openWrite().write('{"index":{"content":"Helllo"}}');
print("Operation finish");
}
})
.then((_) => data.readAsString())
.then((content) => JSON.decode(content))
.catchError((e) => new Map());
}
void main()
{
HttpServer.bind('127.0.0.1', 8080)
.then((server) {
print("Server is lauching... $server");
server.listen((HttpRequest request) {
request.response.statusCode = HttpStatus.ACCEPTED;
ft_get_data()
.then((data_map) {
if (data_map.isNotEmpty)
request.response.write(data_map['index']['content']);
else
request.response.write('Not work');
})
.whenComplete(request.response.close);
});
})
.catchError((error) {
print("An error : $error.");
});
}
3 回答
我试图将您的代码重建为"readable"格式 . 我没有测试过,所以可能会有错误 . 对我来说,如果
.then()
没有嵌套,代码就更容易阅读 . 如果.then()
开始换行,它也有助于阅读 .你不能插入一个then()到另一个 . 需要链接它们 . 否则,返回JSON.decode(data)返回到无处(主事件循环)而不是之前的“then”处理程序
简要说一下,我会说你需要
并使用它
then
内的return
不会从ft_get_data
返回,但仅从then
返回如果涉及异步调用,则可以't continue if it was sync, it'然后异步完全向下 .