javascript - 从 JavaScript 生成器返回值

标签 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???

任何帮助将不胜感激 - 我希望我已经正确解释了自己。

最佳答案

您应该能够使用最后一个 yield aUpdatedTagsCollection;finally { yield aUpdatedTagsCollection;}return aUpdatedTagsCollection;runGenerators 函数并生成最后一个

var receivedData = oImageData.oIterator.next();

从您的 oImageData 对象调用。

关于javascript - 从 JavaScript 生成器返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35531172/

相关文章:

javascript - Angular JS UI 路由

javascript - Angular 模块弹出窗口 : How to obtain data from Ajax/Json

javascript - 如何为在 'mouseover' 上播放()视频的页面上的每个视频添加叠加按钮?

Keras flow_from_directory 限制示例数量

python - 从集合中获取一个或无

node.js - 哟 Angular 误差?

javascript - 如何跟踪 javascript 行为的起源,特别是 - 将哈希添加到我的 url

javascript - 在 Canvas 上渲染文本不起作用

c - main() 前后的函数声明

JavaScript:带有函数数组的TypeError