Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.8k views
in Technique[技术] by (71.8m points)

ts 中数组包裹的 promise 参数如何推导

例如一个函数,接受一个 promise 数组,然后再把这个 promise 数组 return,如何推导出 return 后的 promise 值呢?

例如下面的代码,希望可以推导出 then 中的 res

function afn(fnArr) {
  return Promise.resolve([fnArr[0](), fnArr[1]()])
}

afn([
  function(){
    return new Promise<string>(resolve => resolve('222'))
  },
  () => Promise.resolve(1)
]).then(arr => {
  arr[0].then(res =>  res)
})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
// 更新前
function afn<T>(fnArr: Array<() => Promise<T> > ) {
  return fnArr;
}

type WithPromise<T> = () => Promise<T>;

interface Fn {
  <T>(a: WithPromise<T>): Promise<[Promise<T>]>;
  <T, K>(a: WithPromise<T>, b: WithPromise<K>): Promise<[Promise<T>, Promise<K>]>;
  <T, K, P>(a: WithPromise<T>, b: WithPromise<K>, c: WithPromise<P>): Promise<[Promise<T>, Promise<K>, Promise<P>]>;
  <T, K, P, Q>(a: WithPromise<T>, b: WithPromise<K>, c: WithPromise<P>, d: WithPromise<Q>): Promise<[Promise<T>, Promise<K>, Promise<P>, Promise<Q>]>;
  (...args: Array<WithPromise<any>>): Promise<Array<Promise<any>>>;
}

const fn = ((...args: Array<WithPromise<any>>) => Promise.resolve(args.map((f) => f())) as unknown) as Fn;

fn(
  function () {
    return new Promise<string>((resolve) => resolve('222'));
  },
  () => Promise.resolve(1),
).then((arr) => {
  arr[0].then((res) => res);
});

利用重载,可以自行加到 8- 10 个


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...