使用库 dom-to-image 按顺序返回承诺结果 [英] Return a promise result in order using the library dom-to-image

查看:73
本文介绍了使用库 dom-to-image 按顺序返回承诺结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 dom-to-image 库,我们可以使用 Promises 转换图像.

Using the dom-to-image library we can convert an image using Promises.

使用示例,从DOM对象转换为PNG图片:

Usage example, conversion from DOM object to PNG image:

var node = document.getElementById('my-node');

domtoimage.toPng(node)
    .then(function (dataUrl) {
        var img = new Image();
        img.src = dataUrl;
        document.body.appendChild(img);
    })
    .catch(function (error) {
        console.error('oops, something went wrong!', error);
    });

在幕后,toPng 方法是一个 Promise 对象链:

Behind the scenes, the toPng method is chain of a Promise object:

/**
 * @param {Node} node - The DOM Node object to render
 * @param {Object} options - Rendering options, @see {@link toSvg}
 * @return {Promise} - A promise that is fulfilled with a PNG image data URL
 * */
function toPng(node, options) {
    return draw(node, options || {})
        .then(function (canvas) {
            return canvas.toDataURL();
        });
}

我想根据 Node 数组转换图像,然后按顺序获取这些图像.问题是当我调用 toPng() 时,异步处理时间因 DOM 目标复杂性的函数而异.所以它会在复杂度较低的页面之前返回,而不是按顺序返回页面.

I want to convert images based on a Node array, and then, to get that images in order. The problem is when I call toPng() the async process time varies in function of the DOM target complexity. So it will return before the pages with less complexity, instead of return the pages in order.

let pages = document.querySelectorAll('.page');

pages.forEach(page => {
  let dataUrl = convertToPng(page.firstElementChild);
});

function convertToPng(page) {
  domtoimage.toPng(page)
    .then(function (dataUrl) {
      console.log(page); // prints pages randomly (e.g. page3, page1, page2) 
    })
}

一种可能的解决方案是使用 Promise.all() 方法并使用 forEach() 方法附加所有 Promise.但在这种情况下,我使用的是外部库,我不知道如何处理才能首先获得第 1 页,然后获得第 2 页,依此类推...

A possible solution would be use a Promise.all() method and attach with a forEach() method all the Promises. But in this case, that I'm using an external library, I don't know how to approach in order to get first the page1, then the page 2, and so on...

推荐答案

据我所知,对于这种情况,您可以使用 Promise.all.像这样:

As I understand for this case you can use Promise.all. Smthing like this one:

let pages = document.querySelectorAll('.page');

Promise.all(Array.prototype.slice.call(pages,0)
.map(page =>domtoimage.toPng(page)
).then((pages)=>{.... your handler....});

有关 Promise.all 的更多信息,您可以从 MDN

More information about Promise.all you can get from MDN

这篇关于使用库 dom-to-image 按顺序返回承诺结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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