【问题标题】:Return value from JavaScript GeneratorsJavaScript 生成器的返回值
【发布时间】:2016-06-02 13:16:25
【问题描述】:

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

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

【问题讨论】:

    标签: javascript function generator yield


    【解决方案1】:

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

    var receivedData = oImageData.oIterator.next();
    

    从您的 oImageData 对象调用。

    【讨论】:

    • 嗨,我知道你不能从生成器函数返回数据。我确实通过将回调函数传递给生成器,然后从生成器调用回调,传回 aUpdatedTagsCollection 来解决这个问题。
    • @AndyMeek,这是什么意思? yield 停止执行并返回值,就像 return 运算符一样,但能够从它离开的地方继续。 yield 参数作为generator.next() 调用的返回值,而generator.next() 调用的参数作为yield 语句的返回值。如果您根本不使用生成器的功能,为什么还要费心呢?
    猜你喜欢
    • 2015-06-07
    • 2018-05-02
    • 2021-01-16
    • 2016-06-27
    • 2012-07-02
    • 2021-12-29
    • 2020-09-22
    • 2017-12-29
    • 2019-02-23
    相关资源
    最近更新 更多