Sunday, October 1, 2017

How to convert method created to return a promise with $q library to use an ES6 Promise. Angularjs app to Angular4+

Since the ES6 Promise does not have a deferred object confused on how to go about converting this to work with ES6 Promises. One solution that I was looking at is to add a deffered object manually to the Promise Constructor. see the No deffered section for the example code

Reason: I am converting the angularjs app to angular4 and using it to better understand how to work with ES6 Promises. I was going to add the deferred object, but thought that was too much of a workaround.

 function generateImages() {
        console.log('generateImagesCalled')

        // set up promises
        var fullDeferred = $q.defer();
        var thumbDeferred = $q.defer();

        var resolveFullBlob = blob => fullDeferred.resolve(blob);
        var resolveThumbBlob = blob => thumbDeferred.resolve(blob);

        var displayPicture = (url) => {
            var image = new Image();
            image.src = url;

            // Generate thumb
            var maxThumbDimension = THUMB_IMAGE_SPECS.maxDimension;
            var thumbCanvas = _getScaledCanvas(image, maxThumbDimension);
            thumbCanvas.toBlob(resolveThumbBlob, 'image/jpeg', THUMB_IMAGE_SPECS.quality);

            // Generate full
            var maxFullDimension = FULL_IMAGE_SPECS.maxDimension;
            var fullCanvas = _getScaledCanvas(image, maxFullDimension);
            fullCanvas.toBlob(resolveFullBlob, 'image/jpeg', FULL_IMAGE_SPECS.quality);
        }

        var reader = new FileReader();
        reader.onload = (e) => {
            displayPicture(e.target.result);
        }
        reader.readAsDataURL(vm.currentFile);


        return $q.all([fullDeferred.promise, thumbDeferred.promise]).then(results => {
            console.log(results);
            return {
                full: results[0],
                thumb: results[1]
            }
        });

    }

Source: AngularJS



from Angular Questions https://angularquestions.com/2017/10/01/how-to-convert-method-created-to-return-a-promise-with-q-library-to-use-an-es6-promise-angularjs-app-to-angular4/
via @lzomedia #developer #freelance #web #lzomedia.com

No comments:

Post a Comment