gpt4 book ai didi

dart - 如何按顺序处理异步代码

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

我已经阅读了很多关于此(异步和 future )的帖子和文章,但我不确定当前情况如何。我尝试了许多不同的变体。

我正在尝试按顺序执行以下代码:

import 'dart:async' as async;
import 'dart:io';
import 'dart:math';
import 'package:postgresql/postgresql.dart' as pg;

var uri = 'postgres://admin:admin@localhost:5432/testdb';
List lgNames = ['Peter', 'Robert', 'Mary', 'Marg', 'William',
'Vern', 'Dermot', 'Monty', 'Peggy', 'Sue', 'William'];

List lgUsed = [];

Random rand1 = new Random();

void main() {
pg.connect(uri).then((oDb) {
print ("Connected to database");

fClearTable(oDb).then((String sResult){
print(sResult);

for (int iPos = 0; iPos < 3; iPos++) {
fListTable(oDb, "Select before Insert number ${iPos+1}").then((String sResult) =>
print(sResult));

fInsertData(oDb, "Insert Number ${iPos+1}").then((String sResult) =>
print(sResult));

fListTable(oDb, "Select after Insert number ${iPos+1}").then((String sResult) =>
print(sResult));
}
});
});
}

async.Future<String> fClearTable(oDb) {
async.Completer oCompleter = new async.Completer();
oDb.execute("DELETE FROM test01").then((oResult){
oCompleter.complete("Table has been cleared");
});
return oCompleter.future;
}

async.Future<List> fListTable(oDb, sMsg) {
async.Completer oCompleter = new async.Completer();
oDb.query("SELECT * FROM test01").toList().then((lResult){
String sResult = "$sMsg = $lResult";
oCompleter.complete(sResult);
});
return oCompleter.future;
}

async.Future<String> fInsertData(oDb, sMsg) {
async.Completer oCompleter = new async.Completer();
oDb.execute("Start Transaction").then((oResult){
String sName;
for (bool tFound = true; tFound;) {
int iPos = rand1.nextInt(10);
sName = lgNames[iPos];
tFound = false; // init
for (iPos = 0; iPos < lgUsed.length && !tFound; iPos++){
tFound = (sName == lgUsed[iPos]);
}
}
lgUsed.add(sName);
String sSql = """INSERT INTO test01 (name)
VALUES ('$sName')""";
print("$sSql");
oDb.execute(sSql).then((oVal){
oDb.execute("COMMIT").then((oVal){
oCompleter.complete(sMsg);
});
});
});
return oCompleter.future;
}

该程序的目的是循环三遍,并且:
a) 选择表格
b) 在表格中插入一行。
c) 选择表格

程序的输出在最后清楚地同时显示了所有三个插入。

程序的输出如下:
Connected to database
Table has been cleared
Select before Insert number 1 = []
INSERT INTO test01 (name)
VALUES ('Vern')
Select after Insert number 1 = []
Select before Insert number 2 = []
INSERT INTO test01 (name)
VALUES ('Peter')
Select after Insert number 2 = []
Select before Insert number 3 = []
INSERT INTO test01 (name)
VALUES ('Robert')
Select after Insert number 3 = []
Insert Number 1
Insert Number 2
Insert Number 3

程序终止时 psql 中的 Select 显示:
testdb=# select * from test01;
id | name
-----+--------
157 | Vern
158 | Peter
159 | Robert
(3 rows)

有没有办法实现我想要的 IE。对于插入后的选择显示表中的新值?

欢迎任何相关评论。

最佳答案

开始,here's一篇关于 future 如何在 Dart 中工作的好文章。

您真正需要知道的是,Futures 中的代码在所有同步代码完成后运行。此外,根据定义,Future 是异步完成的,因此期望一个 Future 在另一个 Future 之前完成是不合理的,除非它们被链接起来。

也就是说:

main() {
print('first');
someFutureCall().then((_) => print('second?'));
someOtherFutureCall().then((_) => print('third?'));
print('last?');
}

这将打印:“第一个”然后“最后一个?”然后这两个 Futures 可以按任意顺序完成。您无法确定哪个将首先完成。你所知道的是同步代码首先发生。

要获得正确的顺序,请执行以下操作:
main() {
print('first');
someFutureCall()
.then((_) => print('second?'))
.then((_) => someOtherFutureCall())
.then((_) => print('third?'))
.then((_) => print('last?'));
}

因此,您的示例以不保留顺序的方式使用 Future。你想要的是这个:

void main() {
pg.connect(uri).then((oDb) {
print ("Connected to database");
return fClearTable(oDb);
}).then((String sResult){
print(sResult);
return Future.forEach([0, 1, 2], (i) {
return fListTable(oDb, "Select before Insert number ${iPos+1}")
.then((String sResult) => print(sResult))
.then((_) => fInsertData(oDb, "Insert Number ${iPos+1}"))
.then((String sResult) => print(sResult))
.then((_) => fListTable(oDb, "Select after Insert number ${iPos+1}"))
.then((String sResult) => print(sResult));
});
});
}

另见 API documentation for Futures .

关于dart - 如何按顺序处理异步代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16244247/

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