Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
518 views
in Technique[技术] by (71.8m points)

lodash - using promises in node.js to create and compare two arrays

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...