Skip to content
Advertisement

How can I put elements in Promise.all() array conditionally?

The code below is what I wrote.
I know ‘await’ keyword shouldn’t be in for-loop well.

const booksNotBackedUp: number[] = [];
for (let i = 0; i < usersBooks.length; i += 1) {
        const files = await Util.file.getFiles(Util.file.DATA_BUCKET, { prefix: `${userId}/data/${usersBooks[i]}/sqlite` });
        if (files.length === 0) booksNotBackedUp.push(usersBooks[i]);
    }
console.log('booksNotBackedUp', booksNotBackedUp);

So, I tried like this but the ‘result’ contains every elements from ‘userBooks’ and that’s not what I wanted.

const booksNotBackedUp: any[] = [];
userBooks.forEach((book) => {
    booksNotBackedUp.push(Util.file.getFiles(Util.file.DATA_BUCKET, { prefix: `${userId}/data/${book}/sqlite` })
})
const result = await Promise.all(booksNotBackedUp);
console.log('booksNotBackedUp', result);

Please help this poor newbie😥

Advertisement

Answer

Your condition to add the promise into array lies inside the promise result. It is not possible to add the promise in array beforehand as promise is not resolved yet.

You can do the filtering after promise.all() resolved. In that case you will have all the results and you can use array’s filter method.

Advertisement