如何转换创建的方法以返回带有$ q库的promise以使用ES6 Promise。 Angularjs应用于Angular4 + [英] How to convert method created to return a promise with $q library to use an ES6 Promise. Angularjs app to Angular4+

查看:98
本文介绍了如何转换创建的方法以返回带有$ q库的promise以使用ES6 Promise。 Angularjs应用于Angular4 +的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于ES6 Promise没有将延迟对象混淆如何将其转换为与ES6 Promises一起使用。我正在研究的一个解决方案是手动向Promise构造函数添加一个deffered对象。 请参阅示例的无保留部分代码

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

原因:我正在将angularjs应用转换为angular4 并使用它来更好地了解如何使用ES6 Promises。我打算添加延迟对象,但认为这是一个太多的解决方法。

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

    }


推荐答案

特殊情况 resolve 拒绝可以公开以复制延期:

In some special cases resolve and reject can be exposed in order to replicate deferreds:

let pResolve;
let pReject;
const p = new Promise((resolve, reject) => {
  pResolve = resolve;
  pReject = reject;
});

或者可以形成延期对象:

Or deferred object can be formed:

const deferred = {};
deferred.promise = new Promise((resolve, reject) => {
    Object.assign(deferred, { resolve, reject });
});

由于延迟不是承诺内置 - 在功能和易于反模式的情况下,最好只在适用时使用构造函数来解决这个问题。

Since deferreds aren't Promise built-in feature and are prone to be antipattern, it's preferable to solve this with constructor function only, when it is applicable.

在上面的代码中 displayPicture 以及无法立即形成承诺但 load 事件限制了有效处理情况的方式。它可以通过坚持事件的承诺来改进(也有利于进一步转换为 async..await ):

In the code above displayPicture and the fact that promises cannot be formed instantly but on load event limits the ways the situation can be efficiently handled. It can be improved with sticking to promises for events (also beneficial for further conversion to async..await):

    const readerPromise = new Promise(resolve => reader.onload = resolve);
    reader.readAsDataURL(vm.currentFile);

    const blobPromises = readerPromise.then(e => {
      const url = e.target.result;

      const fullBlobPromise = new Promise(resolve => {
        ...
        fullCanvas.toBlob(resolve, ...);
      });

      const thumbBlobPromise = ...;

      return Promise.all([fullBlobPromise, thumbBlobPromise]);
    });

承诺还应该使用Angular摘要以提供相同的控制流。由于承诺内部不依赖于Angular服务,最后可以有一个摘要:

The promises should also make use of Angular digests in order to provide same control flow. Since promise internals don't rely on Angular services, there can be a single digest at the end:

    return blobPromises.then(
      () => $rootScope.$apply(),
      err => {
        $rootScope.$apply();
        throw err;
      }
    );
    // or
    return $q.resolve(blobPromises);

这篇关于如何转换创建的方法以返回带有$ q库的promise以使用ES6 Promise。 Angularjs应用于Angular4 +的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆