0

I needed to compare two arrays the first one a couple of filenames from a database, the second one a list of files I already downloaded to my client. The Idea was to load whatever files are missing on the client. As the reading via fswas two slow, I tried using Promises to wait for one function to finish before the next starts. But somehow I got lost... My code so far:

let filesIneed = [];
let filesIhave = [];
let filesToFetch = [];
getLocalFiles().then(getFilesIneed).then(getfilesToRetreive);

function getLocalFiles() {
    fs.readdir(localPath, (err, files) => {
        files.forEach(file => {
                filesIhave.push(file)
        });
    })
    return Promise.all(filesIhave);
}

function getFilesIneed () {
    for (let x of docs) {//this is my JSON
        filesIneed.push(y.NameOfFileIShouldHave);
        }
    }
    return Promise.all(filesIneed);
}

function getfilesToRetreive() {
    filesToFetch = _.difference(filesIneed, filesIhave);
    return Promise.all(filesToFetch);
}


console.log(filesToFetch);

I do get the first and second array ("filesIneed" and "filesIhave"), but difference is always empty. So maybe I just mangled up the Promises, as this concept is completely new to me and I'm aware I only understood half of it.

Torf
  • 1,154
  • 11
  • 29

1 Answers1

3

This is completely wrong. You cannot run Promise.all on an array of filenames. You can only run it on an array of promises.

There is also no need to push every element of an array one at a time to an empty array just to return that array when you already have that array in the first place.

You cannot use promises to compare two arrays. You can use lodash to compare two arrays in a then handler of a promise, that resolves to an array.

If you want to get a promise of file names from the fs.readdir then use one of the following modules:

Also don't use global variables for everything because you will have problems with any concurrency.

Also, read about promises. Without understanding how promises work you will not be able to guess a correct way of using them. Even looking at some working code examples can help a lot and there are a lot of questions and answers on stack Overflow about promises:

Community
  • 1
  • 1
rsp
  • 107,747
  • 29
  • 201
  • 177
  • Wow - that's an awful lot - I'll go through them all. Thanks. I know there are some flaws in the Code which are not related to promises, but that's mainly to point out what I was trying. The original piece of code is a bit better and quite different (this is merely an example). – Torf Feb 10 '17 at 14:20