简体   繁体   中英

Make sure function is finished. Javascript

I have the below function. I read several Json files and parse them and want to include them into an array and return that array.Problem is how do I make sure that the function really have read the 5 files on the harddrive? I have tried check if variable i equals fileNameListLength-1 and check if the function have finished that way but it didn't work, the for loop was finished before the fs.readFile functions were finished. So how would you solve this?. Sorry for possible duplicate of question.

var fs = require('fs');
var urlToInfo = '/home/user/data';

function getRawData() {
    var fileNameList = ['file_1', 'file_2', 'file_3', 'file_4', 'file_5'];
    var fileNameListLength = fileNameList.length;
    var rawDataArray = new Array();
    for (var i = 0; i < fileNameListLength; i++) {
        var url = urlToInfo + "/Data/" + fileNameList[i] + ".json";
        fs.readFile(url, 'utf8', function (err, data) {
            if (err) {
                return console.log(err);
            }
            try {
                var portalData = JSON.parse(data);
                rawDataArray[fileNameList[i]] = portalData;
            } catch (e) {
                // Error parsing JSON data
                console.log("Error Parsing Json data.");
                console.log(e);
            }
        });

    }
    //Make sure that all files have been read and that the rawDataArray contains all info
    //return rawDataArray
}

You should check the condition in the readFile cb, this should be easy to do.

But I suggest you can have a try at promise.

var fsp = require('fs-promise');

var files = ['foo1', 'foo2'];

// weird, files.map(fsp.readFile) does not work.
Promise.all(files.map(function (foo) {
    return fsp.readFile(foo);
})).then(function (results) {
    // process data
}, function (err) {
    // error processing
})

You could try using the async library and using the eachSeries function.

var fs = require('fs');
var async = require('async');
var urlToInfo = '/home/user/data';
var rawArray = [];

async.eachSeries(fileNameList, function(fileName,callback){
    var url = urlToInfo + "/Data/" + fileNameList[i] + ".json";
    fs.readFile(url, 'utf8', function (err, data) {
        if (err) {
            return console.log(err);
        }

        try {
            var portalData = JSON.parse(data);
            rawArray.push(portalData);
        } catch (e) {
            // Error parsing JSON data
            console.log("Error Parsing Json data.");
            console.log(e);
        }
    });
}, function(err){
    console.log('the reading of all files finished');
    console.log('array',rawArray);
});

This will execute the function in series and fill the array when all the iterator functions are called, the callback function will be executed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM