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.
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
undefinedor aPromise, but a value will always be returned.If the value is a
Promiseand 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)orawait.So, the short answer to your question depends on what you mean by "this.existingFilesList.filter() function finishes".
I'm assuming that
existingFilesListis a regular array, in which casefilterexecutes synchronously, so the simple answer is "Yes... the second if conditional waits until this.existingFilesList.filter() function finishes."If, however,
existingFilesListis some custom object or class andfilter()returns a Promise, then you have a bug becausethis.existingFilesListwill be set to the returnedPromiseand "the second if conditional" will not wait for the Promise to be resolved. It will keep on trucking andthis.existingFilesList.length == 0will evaluate asfalsebecauseundefined == 0isfalse.Some free advice:
If possible, I would highly recommend using the
asyncandawaitkeywords. It is much easier to read and understand what is going on and leads to fewer bugs. (If, for example, yourexistingFilesListis something other than an array andfilterreturns aPromise, then you could add anawaitin front of it without needing to start a new.then()chain)