Reputation: 1
I just have a basic question about order of execution in JS code.
deleteAttachement({ cdId, paId: recordId }).then(response => {
if (response) {
this.existingFilesList = this.existingFilesList.filter(file => (file.contentVersionId != cvId));
}
if(this.existingFilesList.length == 0) {
this.statusIcon = this.missingIcon;
}
}).catch(err => {
console.log(err);
});
Im trying to change the Icon based on the amount of records contained in the member variable "this.existingFilesList" (Its an array).
Im just wondering if in the code above, the second if conditional waits untill this.existingFilesList.filter() function finishes and the member variable is updated, or the filter() function just runs asynchronously in the background and as soon as it is called, the if conditional is called practically at the same time without waiting for the this.existingFilesList update.
It seems like it works and wait for it, but Im not sure if its due to the short amount of records.
Upvotes: 0
Views: 36
Reputation: 25875
this.existingFilesList.filter(file => (file.contentVersionId != cvId));
Every function call in JavaScript always returns a value immediately. (Unless an exception is thrown, but I hope that is obvious.)
The value might be undefined
or a Promise
, but a value will always be returned.
If the value is a Promise
and your were expecting an array or some other value, then you have a bug in your code. You need to wait for the Promise to resolve using either .then(callback)
or await
.
So, the short answer to your question depends on what you mean by "this.existingFilesList.filter() function finishes".
I'm assuming that existingFilesList
is a regular array, in which case filter
executes synchronously, so the simple answer is "Yes... the second if conditional waits until this.existingFilesList.filter() function finishes."
If, however, existingFilesList
is some custom object or class and filter()
returns a Promise, then you have a bug because this.existingFilesList
will be set to the returned Promise
and "the second if conditional" will not wait for the Promise to be resolved. It will keep on trucking and this.existingFilesList.length == 0
will evaluate as false
because undefined == 0
is false
.
Some free advice:
If possible, I would highly recommend using the async
and await
keywords. It is much easier to read and understand what is going on and leads to fewer bugs. (If, for example, your existingFilesList
is something other than an array and filter
returns a Promise
, then you could add an await
in front of it without needing to start a new .then()
chain)
async function deleteStuff() {
try {
const response = await deleteAttachement({ cdId, paId: recordId });
if (response) {
this.existingFilesList = this.existingFilesList.filter(file => (file.contentVersionId != cvId));
}
if(this.existingFilesList.length == 0) {
this.statusIcon = this.missingIcon;
}
} catch (err) {
console.log(err);
}
}
Upvotes: 0