Magician
Magician

Reputation: 2123

Node.js: Single variable, multiple promises

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?

Upvotes: 0

Views: 157

Answers (2)

Bergi
Bergi

Reputation: 665584

  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};
    });
}

Upvotes: 5

Amit Wagner
Amit Wagner

Reputation: 3274

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)
            })

    })
}

Upvotes: -1

Related Questions