在Dart中我有Completer
返回Future
(承诺),Future
可以在其他地方完成,然后创建它,比如
class SomeClass {
final Completer<bool> initializationDone = new Completer<bool>();
SomeClass() {
_doSomeAsyncInitialization();
}
void _doSomeAsyncInitialization() {
// some async initialization like a HTTP request
fetchDataFromServer().then((data) {
processData();
initializationDone.complete(true);
});
}
}
main() {
var some = new SomeClass();
some.initializationDone.future.then((success) {
// do something.
});
}
我不想要解决这个实际问题,这只是我想出的一个例子,用于演示如何在Dart中使用Completer
。
什么是TypeScript中的Dart Completer
等同于什么?
答案 0 :(得分:3)
制作了这个对我有用的简单类:
export class Completer<T> {
public readonly promise: Promise<T>;
public complete: (value: (PromiseLike<T> | T)) => void;
private reject: (reason?: any) => void;
public constructor() {
this.promise = new Promise<T>((resolve, reject) => {
this.complete = resolve;
this.reject = reject;
})
}
}
const prom = new Completer<bool>();
prom.complete(true);
答案 1 :(得分:0)
这看起来像是在TypeScript https://github.com/angular/angular/blob/b0009f03d510370d9782cf76197f95bb40d16c6a/modules/angular2/src/facade/promise.ts
中实现了这样的Completer
export {Promise};
export interface PromiseCompleter<R> {
promise: Promise<R>;
resolve: (value?: R | PromiseLike<R>) => void;
reject: (error?: any, stackTrace?: string) => void;
}
export class PromiseWrapper {
static resolve<T>(obj: T): Promise<T> { return Promise.resolve(obj); }
static reject(obj: any, _): Promise<any> { return Promise.reject(obj); }
// Note: We can't rename this method into `catch`, as this is not a valid
// method name in Dart.
static catchError<T>(promise: Promise<T>,
onError: (error: any) => T | PromiseLike<T>): Promise<T> {
return promise.catch(onError);
}
static all(promises: any[]): Promise<any> {
if (promises.length == 0) return Promise.resolve([]);
return Promise.all(promises);
}
static then<T, U>(promise: Promise<T>, success: (value: T) => U | PromiseLike<U>,
rejection?: (error: any, stack?: any) => U | PromiseLike<U>): Promise<U> {
return promise.then(success, rejection);
}
static wrap<T>(computation: () => T): Promise<T> {
return new Promise((res, rej) => {
try {
res(computation());
} catch (e) {
rej(e);
}
});
}
static scheduleMicrotask(computation: () => any): void {
PromiseWrapper.then(PromiseWrapper.resolve(null), computation, (_) => {});
}
static isPromise(obj: any): boolean { return obj instanceof Promise; }
static completer(): PromiseCompleter<any> {
var resolve;
var reject;
var p = new Promise(function(res, rej) {
resolve = res;
reject = rej;
});
return {promise: p, resolve: resolve, reject: reject};
}
}