これは私のコードです。ご覧のとおり、私はルートレベルで約束を集める必要があります。私の目的は、ジオコーディングされたデータを含むファイル名を含む約束の集まりを得ることです。
var
_ = require('lodash'),
path = require('path'),
pkg = require(path.join(__dirname, 'package.json')),
fs = require('fs'),
promise = require('bluebird'),
exif = require('exif').ExifImage,
geocoder = promise.promisifyAll(require('geocoder')),
exec = require('child_process').exec,
config = require('nconf').file({
file: path.join(__dirname, 'config.json')
});
var geocodePromises = []; // I want to collect all promises here
fs.readdir(path.join(__dirname, 'files'), function (err, files) {
files.filter(function (file) {
var ext = file.split('.').pop(),
cond;
cond = file; // File needs to exist
cond = cond && file[0] != '.'; // Exclude hidden files
cond = cond && config.get("files:support").indexOf(ext) > -1; // File needs to be supported
return cond;
}).forEach(function (file) {
file = path.join(__dirname, 'files/') + file;
new exif({
image: file
}, function (err, data) {
if (!err) {
if (data.gps) {
var location = parseGPS(data.gps); // Obtain lat & lng
geocodePromises.push(geocoder.reverseGeocodeAsync(location.lat, location.lng));
} else {
console.log("Error: GPS data not available");
}
} else {
console.log("Error: " + err);
}
});
});
Promise.all(geocodePromises).then(function (result) {
console.log(result); // Returns an empty array []
// Each result should contain the filename and geocoded location
/*
Example:
{
"file": "1.jpg",
"location": {
<google reverseGeocode object>
}
}
*/
});
//exec('killall Finder');
});
function parseGPS(gps) {
var lat = gps.GPSLatitude,
lng = gps.GPSLongitude,
latRef = gps.GPSLatitudeRef || "N",
lngRef = gps.GPSLongitudeRef || "W";
// Convert coordinates to WGS84 decimal
lat = (lat[0] + lat[1]/60 + lat[2]/3600) * (latRef == "N" ? 1 : -1);
lng = (lng[0] + lng[1]/60 + lng[2]/3600) * (lngRef == "W" ? -1 : 1);
// Return lat, lng
return {
lat,
lng
};
};
まさにこのような問題に対処するための[async'](https://www.npmjs.com/package/async)という素敵なnpmパッケージがあります。 –
なぜ待つ?ブルーバードの約束を使用してください。 Promise.mapはリクエストを抑制することさえできます。啓発を求める。 – Wainage
[非同期呼び出しからの応答を返すにはどうすればいいですか?](http://stackoverflow.com/q/14220321/218196) –