0

I want to create multiple promises, and I really don't care about race in this code, as long as all callbacks are done.

So, I have a variable, which holds all data, let's say:

export interface IData {
    data1: string[],
    data2: string[],
    data3: string[]
}

Those 3 are unrelated, and I have a data fetcher.. say:

function getData(id: string): Promise<IData> {
    return new Promise((resolve, reject) => {
        var data = new TableFetcher();
        data.get(_id)
        .then((result : IData) => {
            resolve()
        })
    })
}

Now, I want to make something like:

function x(): Promise<IData> {
    return new Promise((resolve,reject) => {
        var data: IData = {
            data1: getData('100'),
            data2: getData('200'),
            data3: getData('300')
        }
        resolve(data)
    })
}

when all getData promises has finished.

It doesn't need to chain but all can be run separately, but I need to return an array containing all asynchronous data after they are done.

How can I do that?

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Magician
  • 1,944
  • 6
  • 24
  • 38

2 Answers2

5
  1. Avoid the Promise constructor antipattern!
  2. Use Promise.all to make a promise for the results from an array of promises:

function getData(id: string): Promise<string[]> {
    return new TableFetcher().get(id);
}
function x(): Promise<IData> {
    return Promise.all([
        getData('100'),
        getData('200'),
        getData('300')
    ]).then(([data1, data2, data3]) => {
        return <IData>{data1, data2, data3};
    });
}
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • I saw `promise.all` construct, but I can't find `reject` there. How can I send `reject` to x()'s caller? – Magician Oct 28 '17 at 08:35
  • 1
    @Magician if any of the promises passed to Promise.all() is rejected, the resulting promise will also be rejected. – Thomas Oct 28 '17 at 08:43
  • yes, I know it is rejected, but I need to pass error data to x() caller. something like X.then().catch(here=>console.log(here)); – Magician Oct 28 '17 at 08:50
  • 1
    @Magician Yes, exactly like that. Any error from one of the `getData(…)` promises will reject the returned promise and can be caught with `x().….catch(err => …)`. – Bergi Oct 28 '17 at 08:56
-1

function x(): Promise<IData> {
    return new Promise((resolve, reject) => {
        Promise.all([getData('100'), getData('200'), getData('300')])
            .then(result => {
                var data: IData = {
                    data1: result[0],
                    data2: result[1],
                    data3: result[2]
                }
                resolve(data)
            })
            .catch(err => {
                reject(err)
            })

    })
}
Amit Wagner
  • 3,134
  • 3
  • 19
  • 35