-3

我对如何使用承诺有点困惑。我已经阅读了一些关于 Promise 的内容,主要是因为我似乎必须使用它们。我正在开发一个小型应用程序,该应用程序应该使用 pdfjs 搜索一些 pdf,并且它们使用 Promise。通过查看网上的各种示例,我在 nodejs 中找到了一些东西,但我遇到了一个问题。

我们先来看代码:

require('pdfjs-dist');
var fs = require('fs');

//var searchTerm = "course";
var searchTerm = "designee";
//var searchTerm = "document";
var wordCounter = 0;
var searchResultJSON = [];
//var data = new Uint8Array(fs.readFileSync('testPdf.pdf'));
//var data = new Uint8Array(fs.readFileSync('advanced-javascript.pdf'));
var data = new Uint8Array(fs.readFileSync('iss4.pdf'));
PDFJS.getDocument(data).then(function (pdfDocument) {
  console.log('Number of pages: ' + pdfDocument.numPages );
  //var div = document.getElementById('viewer');
  for(var i = 1; i<=pdfDocument.numPages; i++ ){//loops thru pages
      console.log("i is " + (i));
      pdfDocument.getPage((i)).then(function(page){//get page(i), 
         // console.log("page is " + (i));
          //console.log("inside getPage()");
          page.getTextContent().then( function(textContent){//get content of pdf
            //console.log("inside getTextContent()");  
            //if( null != textContent.items ){
                var page_text = "";
                var last_block = null;
                var lineWithResult = "";

                for( var k = 0; k < textContent.items.length; k++ ){
                    var block = textContent.items[k];
                    //console.log("word " + textContent.items.length + " k is " + k );
                    /* if( last_block != null && last_block.str[last_block.str.length-1] != ' '){
                        if( block.x < last_block.x )
                            page_text += "\r\n"; 
                        else if ( last_block.y != block.y && ( last_block.str.match(/^(\s?[a-zA-Z])$|^(.+\s[a-zA-Z])$/) == null ))
                            page_text += ' ';
                    } */

                    page_text += block.str;

                    last_block = block;
                    lineWithResult = searchPdf(block.str);
                    if(lineWithResult != null){
                        console.log(lineWithResult + " wordCounter is " + wordCounter);

                    }

                }//end of for(var k...)
                    //console.log(" page_text " + page_text);
                    //console.log(searchResultJSON);

            //}
          });//end of textContent.items

      });//end of getPage

  }//end of loop      
});
function searchPdf(toSearch){//searching pdf for searchTerm
    var result = toSearch.toLowerCase().indexOf(searchTerm);
    if(result >=0){//if match is found
        wordCounter++;
        //console.log("toSearch " + toSearch + " result is " + result + " wordCounter " + wordCounter);
        constructResult(toSearch, result);//build the result object
        return toSearch;
    }
    else{//if match not found
        return null;
    }

}
function constructResult(toSearch, result){//construct array of objects containing: search term, search result and index of search term
    searchResultJSON.push({
        "TextLine":toSearch,
        "SearchTerm":searchTerm,
        "Result": result,               
    });     
} 

这段代码的目的是:

  • 循环浏览 pdf 的页面

  • 循环浏览内容

  • 逐行获取变量中的pdf文本

  • 使用关键字搜索 pdf 内容

  • 如果关键字找到匹配项,则打印匹配项

  • 获取 javascript 对象中的匹配项

所以,一切正常,但你会注意到,从第二个 for 循环内部(我得到 pdf 的文本)我调用了一个函数,searchPdf()它基本上执行搜索,并在该函数中我调用另一个constructResult(...)函数应该使用结果创建 javascript 对象。

我在打印这个对象时遇到了一些问题,因为如果我在 for 循环范围之外打印它,它是空的,因为打印调用(在我的情况下是 console.log)在循环实际复制和分析之前执行(读取过程并找到匹配项)文本。所以,promise 看到了解决问题的方法。问题是,我不确定如何以这样一种方式编写代码,以便我可以链接承诺并在所有内容执行后打印我的对象。任何想法?

编辑:所以要澄清一下,我需要依次是:1)循环通过pdf(我将不得不修改代码以很快在某个时候循环通过pdf集合)2)获取每一行文本3)检查有一个匹配 4)如果是这样,复制 javascript 对象中的文本行 5)打印 javascript 对象

4

1 回答 1

1

尝试这样的事情:

function search(doc, s) {
    var allPages = [],
        i;

    for (var i = 1; i <= doc.numPages; i++) {
        allPages.push(doc.getPage(i));
    }

    // Promise.all returns a promise that resolves once 
    // each promise inside allPages has been resolved
    return Promise.all(allPages)
    // pages now contains an array of pages, loop over them
    // using map, return the promise to get the content for each page
    // return it through Promise.all so we can run the next phase
    // once the text is resolved for each page
    .then(pages => Promise.all(pages.map(p => p.getTextContent())))
    // We now have an array of contents for each page, filter based
    // on the passed string
    .then(content => content.filter(c => c.indexOf(s) > -1));
}

// This is a mock of the pdf API used in your question
var pdfDocument = {
    numPages: 3,
    getPage: function(i) {
        return Promise.resolve({
            getTextContent: function() {
                return Promise.resolve('Page ' + i);
            }
        });
    }
}
于 2016-11-17T21:49:44.560 回答