24

i have a function that accepts an object where each prop is a promise. it waits for all the promise to finish then returns a new object with the same props but now resolved values.

enter image description here

resolved_props.company should be string, not Promise<string>

// TODO: fix the types on this
function promise_props<T>(obj:T):Promise<T> {
  const keys = Object.keys(obj)
  const len = keys.length
  const awaitables = new Array<T>(len)
  for (var i = 0; i < len; i++) awaitables[i] = (obj as any)[keys[i]]

  return Promise.all(awaitables).then((results) => {
    const byName:any = {}
    for (var i = 0; i < len; i++) byName[keys[i]] = results[i]
    return byName
  })
}
1
  • 1
    You need to install typescript@next or wait for TypeScript 2.8 to be released. It will bring conditional types which allows to unwrap a promise type.
    – Tao
    Feb 23, 2018 at 10:39

3 Answers 3

48

Typescript 4.5

Utility type Awaited is officially built in typescript v4.5.

https://devblogs.microsoft.com/typescript/announcing-typescript-4-5/#awaited-type

// A = string
type A = Awaited<Promise<string>>;

// B = number
type B = Awaited<Promise<Promise<number>>>;

// C = boolean | number
type C = Awaited<boolean | Promise<number>>;
3
  • About time TS!!! thanks! Feb 3, 2022 at 22:09
  • Neat! This should be the accepted answer now. Mar 5, 2022 at 6:57
  • 1
    And if for some reason you are not able to upgrade to TypeScript 4.5+, you could use Awaited from the ts-essentials package: import { Awaited } from "ts-essentials". npmjs.com/package/ts-essentials#awaited-type
    – joshden
    Aug 3, 2022 at 21:21
15

Your types are not accurate enough and the TypeScript compiler cannot figure it out that they are not promises at that point.

What you need is something like this:

async function promise_props<T>(obj: {[key: string]: Promise<T>}): Promise<{[key: string]: T}> {
    const keys = Object.keys(obj);
    const awaitables = keys.map(key => obj[key]);

    const values = await Promise.all(awaitables);
    const result: {[key: string]: T} = {};

    keys.forEach((key, i) => {
        result[key] = values[i];
    });
    return result;
}

But it will only work if your object has promises of the same type, for example:

{
    company: Promise.resolve("company"),
    page: Promise.resolve("1")
};

I'm not sure if it is possible to get it working with various promise types in the current TypeScript version, but as Tao also suggested, you can use the new features in TypeScript 2.8 to get it working:

type UnPromisifiedObject<T> = {[k in keyof T]: UnPromisify<T[k]>}
type UnPromisify<T> = T extends Promise<infer U> ? U : T;

async function promise_props<T extends {[key: string]: Promise<any>}>(obj: T): Promise<UnPromisifiedObject<T>> {
    const keys = Object.keys(obj);
    const awaitables = keys.map(key => obj[key]);

    const values = await Promise.all(awaitables);
    const result = {} as any;

    keys.forEach((key, i) => {
        result[key] = values[i];
    });
    return result as UnPromisifiedObject<T>;
}

async function main() {
    const x = {
        company: Promise.resolve("company"),
        page: Promise.resolve(1)
    };
    const res = await promise_props(x);
    const company = res.company;  // company is a string here
    const page = res.page;        // page is a number here
}

As you can see, the return type is properly inferred. I think the implementation of the method can be improved. I couldn't find a way to instantiate an instance of the return type and use any, but although compiler cannot infer it, it's type safe as we resolve all promises.

3
  • the 2.8 version works! thanks for writing it for me because it's pretty complicated.. i couldn't figure it out
    – Farzher
    Feb 23, 2018 at 19:59
  • @StephenBugsKamenar I was playing around again with this example, I think my first answer was not quite correct. In particular, I think the definition promise_props<T>(obj: {[k in keyof T]: Promise<T[k]>}) was not good, because it was wrapping a promise inside promise if we consider T[k] was also a promise. Now I've updated it. It's simpler and uses the same implementation as the 2.7 version. I will give it another shot when 2.8 is officially out.
    – Wickoo
    Feb 24, 2018 at 9:09
  • I'm stuck in typescript v4.2.4 that doesn't have the built-in Awaited type. I used your UnPromisify renamed into Awaited and worked perfectly. Thank you!
    – maninak
    Jan 24, 2022 at 17:27
13

after typescript 2.8, i was able to use the following strategy

export type Await<T> = T extends Promise<infer U> ? U : T
export type AwaitProps<T> = {[P in keyof T]: Await<T[P]>}

export async function concurrent<T>(obj: T): Promise<AwaitProps<T>> {
    const keys = Object.keys(obj)
    const awaitables = keys.map(key => obj[key])
    const values = await Promise.all(awaitables)
    const result = {}
    keys.forEach((key, i) => result[key] = values[i])
    return <AwaitProps<T>>result
}

and the usage looks like this

const {claimRow, profileRow} = await concurrent({
    claimRow: claimTable.one(identify(userId)),
    profileRow: profileTable.one(identify(userId)),
})

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.