持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第7天,点击查看活动详情
Dart 中没有 Promise,可以使用 Completer 创建 Future 模拟 Promise 构造函数封装异步代码。
Future<dynamic> promiseWapper() {
final completer = Completer();
MsgConnection connection = MsgConnection();
connection.on('connect', (dynamic data) {
return completer.complete(true);
});
connection.on('disconnect', (dynamic data) {
return completer.complete(false);
});
return completer.future;
}
调用的代码:
promiseWapper().then((connected){
print(connected);
});
需求
最近基于 EventEmitter 开发了一个库,在写单元测试时,需要使用异步测试,js 中直接使用 Promise 封装一下就可以了。
const p = new Promise((resolve, reject) => {
const mc = new MsgConnection();
mc.on('connect', () => {
resolve(true);
});
mc.on('disconnect', () => {
resolve(false);
});
});
p.then((data) => {
// some code
}).catch((error) => {
// some code
});
Dart 语言中没有 Promise,类似的概念是 Future
Future
网上关于 dart 异步编程的资料大多数都是在讲 Future,Future 和 js 中 Promise 基本可以对应起来:
Future.value==Promise.resolveFuture.error==Promise.rejectFuture.wait==Promise.allFuture.any==Promise.race
Completer
Future 的使用方式和 JS 中的 Promise 基本一致,但是 JS Promise 的构造函数的方式没有办法通过 Future 实现,这种需求可以通过 Completer 来满足。
Completer 的说明可以参考这个文档:Flutter 只知道 Future 还不够,你还需要 Completer
解决方案代码
Future<dynamic> promiseWapper() {
final completer = Completer();
MsgConnection connection = MsgConnection();
connection.on('connect', (dynamic data) {
return completer.complete(true);
});
connection.on('disconnect', (dynamic data) {
return completer.complete(false);
});
return completer.future;
}
promiseWapper().then((connected){
print(connected);
});