バッチで promise を処理し、それらが与えられたキーに基づいて結果を返すクラスを作成しましたorder。customerそれらのキーをプロパティとして、解決された値をそれぞれの値として。
したがって、このクラスの使用方法は次のとおりです。
const batchPromiseHandler = new BatchPromise();
// getCustomerInfo and getPaymentInfo will give back a promise which resolves into their data
batchPromiseHandler.add('order', getOrderInfo());
batchPromiseHandler.add('customer', getCustomerInfo());
// await to resolve all into result object
const result = await batchPromiseHandler.resolveAll();
console.log(result.order); // <<-- I want to be able to get suggestion order or customer from IDE
console.log(result.customer);
そして、実際の実装は次のとおりです。
type resultDecorator = (data: any[], index: number) => any;
class BatchPromise {
private promiseList: Promise<any>[] = [];
private keyList: string[] = [];
private decoratorList: resultDecorator[] = [];
add(key: string, promise: Promise<any>, decorator?: resultDecorator): void {
if (this.keyList.indexOf(key) !== -1) {
throw new Error(`Key: "${key}" already exists in PromiseLand!`);
}
this.promiseList.push(promise);
this.keyList.push(key);
this.decoratorList.push(decorator);
}
async resolveAll(): Promise<{ [key: string]: any }> { // <<------ here is naive return type
const resolvedArray = await Promise.all(this.promiseList);
const result = {};
for (let index = 0; index < this.promiseList.length; index++) {
const key = this.keyList[index];
result[key] =
typeof this.decoratorList[index] === 'function'
? await this.decoratorList[index](resolvedArray[index], index)
: resolvedArray[index];
}
return result;
}
}
期待どおりに機能しますが、関数の結果に対してオートコンプリートを取得できるようにしたいと考えていresolveAllます。言語の動的型機能の使い方がわからないので、次のようにしました。
Promise<{ [key: string]: any }>
たとえば、IDEから取得しorderたり提案したりできるようにリファクタリングするにはどうすればよいですか?customer