我刚开始在我的 JS 中使用生成器,我已经了解了其中的一些内容,但我对如何从它们返回数据感到困惑。在下面的生成器函数 (runGenerators) 中,我成功地进行了三个异步调用并获取了返回的数据,但是我不知道如何从生成器函数返回最终数据 (aUpdatedTagsCollection)。
这是我的发电机:
ImageData.prototype.runGenerators = function* runGenerators() {
let aImages, aTagsCollection, aUpdatedTagsCollection;
aImages = yield this.getImagesFromFolder();
aTagsCollection = yield this.getImageData(aImages);
aUpdatedTagsCollection = yield this.findCountry(aTagsCollection);
console.log(aUpdatedTagsCollection); //This prints the correct result, but how do I return it
};
每个方法(getImagesFromFolder、getImageData 和 findCountry)都调用 this.oIterator.next(data);完成后的下一个迭代器,将数据发送到下一个方法。
这是我的 findCountry 方法:
ImageData.prototype.findCountry = function findCountry(aTagsCollection) {
let oSelf = this,
j = 0;
for (var i = 0; i < aTagsCollection.length; i++) {
geocoder.reverse({
lat: aTagsCollection[i].GPSLatitude.description,
lon: aTagsCollection[i].GPSLongitude.description
}, function (oError, oResult) {
if (oResult !== undefined && oResult[0] !== undefined) {
aTagsCollection[j].country = oResult[0].country;
aTagsCollection[j].countryCode = oResult[0].countryCode;
if ((j + 1) === aTagsCollection.length) {
oSelf.oIterator.next(aTagsCollection);
}
}
j++;
});
}
}
这是调用生成器函数的方法
ImageData.prototype.retrieveImageData = function retrieveImageData() {
this.oIterator = this.runGenerators();
this.oIterator.next();
};
最后,这是实例化 ImageData 类并调用 retrieveImageData 方法的方法
let oImageData = new ImageData();
let retrievedData = oImageData.retrieveImageData();
console.log(retrievedData); //undefined (obviously) because isn't returning anything but what/how do I return???
任何帮助将不胜感激 - 我希望我已经正确解释了自己。
最佳答案
您应该能够使用最后一个 yield aUpdatedTagsCollection;
或 finally { yield aUpdatedTagsCollection;}
或 return aUpdatedTagsCollection;
在 runGenerators
函数并生成最后一个
var receivedData = oImageData.oIterator.next();
从您的 oImageData
对象调用。
关于javascript - 从 JavaScript 生成器返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35531172/