Donate. I desperately need donations to survive due to my health

Get paid by answering surveys Click here

Click here to donate

Remote/Work from Home jobs

Pushing to array in an asynchronous function

I am using a javascript library to create isochrones. The script works, but the only remaining question is how to push each feature to the fts array so that it collects all of the features of each output.

When I run the script below, the console logs an empty array immediately because the isochrone() function has not finished running.

I am new to asynchronous function and would appreciate any guidance on where to use forEach, or whether or not to use a promise, or whether it is more efficient to use the ES6 way (async - await).

In general I'd like to know what is wrong below and how/where to write the function so that it "waits" for all instances of

 for (var i = 0; i < output.length; i++){
            fts.push(output[i]);
             }

to finish running. The script is below:

isochrone = require('./isochrone.js');
var turf = require('@turf/turf');
var fs = require('fs'),
obj

token = 'mytoken'


fs.readFile('stops.geojson', handleFile);


function handleFile(err, data) {
    if (err) throw err
    obj = JSON.parse(data)
    features = obj.features


    fts = [];

    for (var i = 0; i < 5; i++) {

    coords = features[i].geometry.coordinates

    isochrone(coords, {"token":token, "threshold":600, "mode":"walking"}, function(err, output){

        if (err) throw err;
        output = output.features

            for (var i = 0; i < output.length; i++){
            fts.push(output[i]);
             }
//      
        });

   }

console.log(fts)

}

Comments