nodejs异步等待/异步未按预期工作

时间:2018-11-13 02:07:06

标签: node.js async-await

这是我的代码,应该在执行下一行之前从findRecords函数获取查询结果。

const FsPool = module.exports = function(dir) {
    events.EventEmitter.call(this)
    this.dir = dirpath;
    this.files = [];
    this.active = [];
    this.threads = 1;
    this.on('run', this.runQuta.bind(this))
};
// So will act like an event emitter
util.inherits(FsPool, events.EventEmitter);

FsPool.prototype.runQuta = function() {
    if (this.files.length === 0 && this.active.length === 0) {
        return this.emit('done');
    }
    if (this.active.length < this.threads) {
        const name = this.files.shift()

        this.active.push(name)
        const fileName = path.join(this.dir, name);
        const self = this;
        fs.stat(fileName, function(err, stats) {
            if (err)
                throw err;
            if (stats.isFile()) {
                fs.readFile(fileName, function(err, data) {
                    if (err)
                        throw err;
                    self.active.splice(self.active.indexOf(name), 1)
                    self.emit('file', name, data);
                    self.emit('run');

                });
            } else {
                self.active.splice(self.active.indexOf(name), 1)
                self.emit('dir', name);
                self.emit('run');
            }
        });
    }
    return this
};
FsPool.prototype.init = function() {
    const dir = dirpath;
    const self = this;
    fs.readdir(dir, function(err, files) {
        if (err)
            throw err;
        self.files = files
        self.emit('run');
    })
    return this
};
const fsPool = new FsPool(__dirname)

fsPool.on('file', async function(fileName, fileData) {
    //console.log('file name: ' + fileName);
    //console.log('file data: ', fileData.toString('utf8'));

    let nctid = fileName.split('.');
    nctid = nctid[0];
    console.log(nctid);

    getData(fileData.toString('utf8'), function(returnValue) {
         fs.writeFile(fpath +  nctid + '.json', returnValue.trim(), 'utf8', function (err) {
                if (err) {
                    return console.log(err);
                }
                console.log("The file was saved!");
            });
        });
    }


})

fsPool.on('dir', function(dirName) {
    console.log('dir name: ' + dirName);

})
fsPool.on('done', function() {
    console.log('done');
});

const findRecords = (collection, myobj) => {
        return new Promise((resolve, reject) => {
            collection.find(myobj).toArray((err, data) => {
                if (err) {
                    console.error(`Cannot find records: ${err}`)
                    reject('error');
                } else {
                    console.log(`Record count: ${data.length}`)
                    resolve(data)
                }
            })
        });
    }


    function getData(data, callback) {
        let jsonO = {
            "results": {},
            "Spots": {},
            "SpotsC": {}
        };

        let jsonspot = [];
        let jsonspotC = [];
        let json = [];

        json.push({});

        const main = async () => {

            let readFileContent = JSON.parse(JSON.stringify(parseXML(data)));
            readFileContent = readFileContent.clinical_study;

            //Spot (city level) and SpotC (country level)
            let lengthdata = 1;
            let country = '';
            let city = '';
            let state = '';
            let name = '';
            let keyidx = 0;
            if (readFileContent.hasOwnProperty('location')) {

                for (let c = 0, len = lengthdata; c < len; c++) {

                    state = state.replace(/[^A-Za-z 0-9]*/g, '').trim();
                    city = city.replace(/[^A-Za-z 0-9]*/g, '').trim();
                    console.log(readFileContent.id_info.id + '|' + country + '|' + state + '|' + city); //<-- This line is keep on printing without waiting for the next line to be complete. Async/Await not working ???

                    if (country != '') {

                        let citylat = 0;
                        let citylng = 0;
                        let countrylat = 0;
                        let countrylng = 0;

                        country = '^' + country + '$';
                        state = '^' + state + '$';
                        city = '^' + city + '$';

                        let query = {
                            country: {
                                '$regex': country,
                                $options: 'i'
                            },
                            state: {
                                '$regex': state,
                                $options: 'i'
                            },
                            city: {
                                '$regex': city,
                                $options: 'i'
                            }
                        };

                        let countrycity = await findRecords(collection, query); 
                        console.log('latlngDB:' + countrycity.length + 'Info:' + country + ' ' + state + ' ' + city);
                    }
                }
            }

            jsonO["results"] = json;
            jsonO["Spots"] = jsonspot;
            jsonO["SpotsC"] = jsonspotC;

            callback(JSON.stringify(jsonO));
        }
        main().catch(console.error);
    }

这是我得到的结果:

00000102|United States|South Carolina|Charleston
00000104|United States|Minnesota|Minneapolis
00000105|United States|Minnesota|Minneapolis
00000106|United States|Wisconsin|Madison
00000107|United States|Vermont|Burlington
00000108|United States|Michigan|Ann Arbor
Record count: 1
latlngDB:1 Info:^United States$ ^South Carolina$ ^Charleston$
Record count: 1
latlngDB:1 Info:^United States$ ^Minnesota$ ^Minneapolis$
Record count: 1
latlngDB:1 Info:^United States$ ^Minnesota$ ^Minneapolis$
Record count: 1
latlngDB:1 Info:^United States$ ^Michigan$ ^Ann Arbor$
NCT00000110|United States|Alabama|Birmingham
Record count: 1
latlngDB:1 Info:^United States$ ^Wisconsin$ ^Madison$

console.log(readFileContent.id_info.id +'|'+国家+'|'+州+'|'+城市); // <-此行将继续打印,而无需等待下一行完成。异步/等待不起作用???

0 个答案:

没有答案