user5481420
user5481420

Reputation:

Wait async process inside array.map wait

I'm using a node.js package called exiftool, which basically is an API to a bash script called exiftool. The process behind is async, and i'm having a hard time to figure it out how to wait the async finish before return all.

That's the code:

  MAP.files = MAP.scan.map((scan) => {
    file = {};
    exiftool.metadata(scan, function(error, metadata) {
      if (metadata) { return file; }
      file.metadata = metadata;
    });
    return file;
  });

So, when i try to access the MAP.files, the result will be several empty object. I understand why, but.. how can i avoid such not desire result?

Thanks.

Upvotes: 1

Views: 1461

Answers (2)

Neutrosider
Neutrosider

Reputation: 572

You can't return the desired result, if you aquire it asynchronously. i would solve it like this (this is untested):

var MapMetadata = function(map, callback)
{
    map.files = {};
    var callbackCount = 0;
    var callbackMaxCount = Object.keys(map.scan).length;
    var metadataCallback = function(key, metadata)
    {
        map.files[key] = metadata;
        callbackCount++;
        if (callbackCount == callbackMaxCount && callback != null)
            callback(map);
    }

    for (var i in map.scan)
    {
        GetMetadata(i, map.scan[i], metadataCallback);
    }
}

var GetMetadata = function(key, scan, callback)
{
    exiftool.metadata(scan, function(error, metadata)
    {
        var result = {};
        if (metadata)
            result.metadata = metadata;

        callback(key, result);
    });
}

MapMetadata(MAP, function(result)
{
    console.log(result);
}

Upvotes: 0

myxobek
myxobek

Reputation: 455

You can use promises to organize asynchronous function behavior, have a look https://www.promisejs.org/

Upvotes: 1

Related Questions