Andy
Andy

Reputation: 121

Return value from JavaScript Generators

I've just started using generators in my JS and I've got my head around bits of it but I'm confused of how to return data from them. In my generator function (runGenerators) below I'm successfully making three async calls and getting the returned data, however I don't know how I return the final data (aUpdatedTagsCollection) back from the generator function.

Here's my generator:

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
};

Each of the methods (getImagesFromFolder, getImageData & findCountry) call the this.oIterator.next(data); next iterator when they are done, sending data to the next method.

This is my findCountry method:

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++;
        });
    }
}

This is the method which calls the generator function

ImageData.prototype.retrieveImageData = function retrieveImageData() {
    this.oIterator = this.runGenerators();
    this.oIterator.next();
};

And, finally this is the method which instantiates the ImageData class and invokes the retrieveImageData method

let oImageData = new ImageData();
let retrievedData = oImageData.retrieveImageData();
console.log(retrievedData); //undefined (obviously) because isn't returning anything but what/how do I return???

Any help would be great appreciated - I hope I've explained myself correctly.

Upvotes: 3

Views: 964

Answers (1)

Redu
Redu

Reputation: 26161

You should be able to use one last yield aUpdatedTagsCollection; or finally { yield aUpdatedTagsCollection;} or return aUpdatedTagsCollection; in the runGenerators function and make a last

var receivedData = oImageData.oIterator.next();

call from your oImageData object.

Upvotes: 1

Related Questions