简体   繁体   中英

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM