在for循环中等待承诺 [英] Waiting for promise in for loop
问题描述
进入这整个异步的东西我有点麻烦。我正在使用pdf.js来读取pdf文件的内容。一切正常,但执行顺序给我带来了麻烦。这是我的代码:
I have a bit of trouble getting into this whole async stuff. I'm using pdf.js to read the contents of a pdf file. Everything is working, however the execution order is causing me troubles. This is the code I have:
function getText(data) {
var contents = [];
PDFJS.getDocument(data).then(function(pdf) {
var numPages = pdf.pdfInfo.numPages;
for (var i = 1; i <= numPages; i++) {
pdf.getPage(i).then(function(page) {
page.getTextContent().then(function(content) {
contents.concat(content.bidiTexts);
})
});
}
})
}
这是按预期工作的,但是,当我们处理所有页面并将其bidiTexts连接到内容时,我想传递内容
。如果我只是在最后一次结束}
之前将带有 contents
的函数调用作为参数,那么它会被提前调用。
This is working as intended, however, I would like to pass contents
when all pages are processed and their bidiTexts are concated to contents. If I just put a function call with contents
as argument before the last closing }
then it gets called to early.
推荐答案
尝试使用承诺:
function getText(data) {
var contents = [];
var promises = [];
PDFJS.getDocument(data).then(function(pdf) {
var numPages = pdf.pdfInfo.numPages;
for (var i = 1; i <= numPages; i++) {
var deferred = $.Deferred(); //Create a deferred object
promises.push(deferred.promise()); //push promise to the list
pdf.getPage(i).then(function(page) {
page.getTextContent().then(function(content) {
contents.concat(content.bidiTexts);
deferred.resolve(); //resolve the deferred object
})
});
}
$.when.apply($,promises).then(function(){ //callback executed when all deferreds are resolved
//do your task with contents
});
})
}
这只是演示如何使用promises。在实际应用程序中,您必须使用 deferred.reject
来处理错误,并在第二次回调中处理它 $。when
This is just a demo how to use promises. In real applications, you have to take care of errors by using deferred.reject
and handle it in the second callback to $.when
这篇关于在for循环中等待承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!