Reputation: 155
I have a loop where I'm comparing 2 databases. At the end of the loop, I'm saving how many changes were made. I need to ensure "LogResults" is run after everything completed.
Something like this works, but is slow due to the 'await' on the 'get'.
for( let i = 0; i < json.data.length; i++ )
{
var newEntry = new PopulateNewEntry( ... );
entryArray.push( newEntry );
await wixData.get( "MyDatabase", newEntry._id ) // <--- Slow
.then( async results => {
if( results === null )
{
//...Async process to write new entry to database.
}
else if( results are different )
{
//...Async process to modify entry in database.
}
})
}
LogResults();
I've seen methods on here that use a promise array and await for all to finish. But I think I'm not sure how to use that while also acting on the promise. All the examples I found do not use a ".then" on the function being waited on.
Something like below, but this does not work. Seems to never finish the 'await'.
var pending = [];
for( let i = 0; i < json.data.length; i++ )
{
var newEntry = new PopulateNewEntry( ... );
entryArray.push( newEntry );
const promise = wixData.get( "MyDatabase", newEntry._id )
.then( async results => {
if( results === null )
{
//...Async process to write new entry to database.
}
else if( results are different )
{
//...Async process to modify entry in database.
}
})
pending.push( promise );
}
const array = await Promise.all( pending );
LogResults();
What am I doing wrong here?
Upvotes: 0
Views: 57
Reputation: 40
@Terry already gave you an answer in the comments but let me expand...
As he already mentioned when you chain the .then
it returns a "settled" promise. Which is not what you want for the Promise.all
.
What you should do is something like this:
const promise = wixData.get( "MyDatabase", newEntry._id );
promise.then(...);
pending.push(promise);
Also unless you really need sync behavior why not instead of using await
for the Promise.all
just chain a .then
to it? Just an idea.
And if you want optimal performance don't wait for each promise to finish one after another, do like you did in the second example and call all the promises then wait for them to all finish.
Upvotes: 1