因此,看来我对 js promises 的理解相当缺乏。我正在使用 PDFJS 将 pdf 的所有页面显示为可滚动的画布列表(当前正在工作)。当我调整窗口大小时,我调用这样的函数(我有一个pages
数组,它存储了来自以下位置的所有 pdf 页面pdf.getPage(index)
:
// PART A
// This part works, though "pages" is a representation obviously
function reRender() {
const pages = [
pdfjsPage0, // the result of pdf.getPage(0)
pdfjsPage1,
pdfjsPage2,
];
return pages.reduce((accum, page, index) => accum.then(() => {
const viewport = page.getViewport(scale);
const canvas = canvases[index];
canvas.width = viewport.width;
canvas.height = viewport.height;
const ctx = canvas.getContext('2d');
const renderContext = {
canvasContext: ctx,
viewport,
};
return page.render(renderContext);
}), Promise.resolve());
}
但是,这段代码不会按预期工作,因为承诺似乎没有像我预期的那样返回:
// PART B
// This part only somewhat works, though "pages" is a representation obviously
// The promise will return and be resolved before all the pages have actually been rendered
// ie: reRender.then(//somecode), //somecode will execute before the pages have been rendered
function reRender() {
const pages = [
pdfjsPage0, // the result of pdf.getPage(0)
pdfjsPage1,
pdfjsPage2,
];
let promise = Promise.resolve(); //edited to add "()"
pages.forEach((page, index) => {
promise = promise.then(() => {
const viewport = page.getViewport(scale);
const canvas = canvases[index];
canvas.width = viewport.width;
canvas.height = viewport.height;
const ctx = canvas.getContext('2d');
const renderContext = {
canvasContext: ctx,
viewport,
};
return page.render(renderContext);
});
});
return promise;
}
然而,当抓取页面时,看起来,Promise 需要以完全不同的方式构建,因为它有效(相同类型的构建不会等待或看起来按照我期望的重新渲染顺序进行:
// PART C
// This works, nothing in the caller.then will execute until everything
// has resolved here
function getPagesAndAddCanvas(pdf, pages = [], canvas = []) {
let promise = Promise.resolve();
for (let i = 1; i <= pdf.numPages; i++) {
promise = promise.then(() => pdf.getPage(i)
.then(page => {
pages.push(page);
const canvas = angular.element('<canvas></canvas>');
containerElement.append(canvas);
canvases.push(canvas[0]);
})
)
}
return promise;
}
然而,在我看来似乎应该起作用,因为 PDFJS.getPage 返回一个承诺,这在某种程度上不起作用,让我对我对承诺的理解感到非常困惑:
// PART D
// This does not work at all, pdf.getPage in this scenario
// does not seem to ever return
function getPagesAndAddCanvas(pdf, pages = [], canvas = []) {
const pageLength = Array(pdf.numPages).fill(1);
return pageLength.reduce((accum, irrelevant, index) => accum.then(() => {
console.log(pdf);
console.log(`index: ${index}`); // this is called for index 0
return pdf.getPage(index)
.then(page => {
console.log(page); // this is NEVER called
pages.push(page);
const canvas = angular.element('<canvas></canvas>');
containerElement.append(canvas);
canvases.push(canvas[0]);
return Promise.resolve(); //edited to fix spelling
});
}), Promise.resolve());
}
自从 PART A 和 PART C 有效,但 PART B 和 PART D 不有效,有没有人了解这些似乎相互矛盾的方式/原因?我在这里碰壁,失去理智。