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?

2 Answers 2

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};
    });
}
Sign up to request clarification or add additional context in comments.

4 Comments

I saw promise.all construct, but I can't find reject there. How can I send reject to x()'s caller?
@Magician if any of the promises passed to Promise.all() is rejected, the resulting promise will also be rejected.
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 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 => …).
-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)
            })

    })
}

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.