从JavaScript生成器返回值

时间:2016-02-21 01:20:53

标签: javascript function generator yield

我刚刚开始在我的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???

任何帮助都会非常感激 - 我希望我已经正确地解释了自己。

1 个答案:

答案 0 :(得分:1)

您应该能够在yield aUpdatedTagsCollection;功能中使用最后一个finally { yield aUpdatedTagsCollection;}return aUpdatedTagsCollection;runGenerators并制作最后一个

var receivedData = oImageData.oIterator.next();

来自您的oImageData对象。