简体   繁体   中英

Changing a loop to Promise.all()

I'm currently iterating through an array, making an api request, waiting for it to resolve, then moving onto the next api call.

I've read of using Promise.all() and I think I could make these api calls in parallel and wait for that promise to resolve, but I'm not exactly sure how to translate what I have here to use Promise.all() .

async lockFolder(folderModel) {
        const driveId = folderModel.driveId;

    // THIS IS WHAT I'D LIKE TO TRANSLATE TO USE Promise.all()
    for (const file of folderModel.docs) {
        let res = await this._lockFile(file.id, driveId);
    }

    // return something....
}

async _lockFile(fileId, driveId) {
    try {
        return await axios.post(myRequestOmittedForBrevity);

    } catch (err) {
        //some error
    }

}

Is there a good way to translate my loop to Promise.all() ? Can I still use await for it's response? Most examples I've seen use .then() but I've been trying to stick with await . Any help is appreciated!

It makes total sense to use Promise.all or Promise.allSettled for this, as soon your requests aren't dependent on each other. It can be something like this:

async lockFolder(folderModel) {
        const driveId = folderModel.driveId;

    // THIS IS WHAT I'D LIKE TO TRANSLATE TO USE Promise.all()
    const listOfPendingPromises = folderModel.docs.map(file => this._lockFile(file.id, driveId))

    const resultArray = await Promise.all(listOfPendingPromises)

    // return something....
}

async _lockFile(fileId, driveId) {  
        return await axios.post(myRequestOmittedForBrevity);
}

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