Merge pull request #4709 from pramodhkp/refactoring

Remove legacy promises from api.js
This commit is contained in:
Yury Delendik 2014-05-01 11:10:03 -05:00
commit aab48a2169
2 changed files with 146 additions and 151 deletions

View File

@ -19,7 +19,7 @@
isStream, Lexer, Page, Parser, Promise, shadow, isStream, Lexer, Page, Parser, Promise, shadow,
stringToPDFString, stringToUTF8String, warn, isString, stringToPDFString, stringToUTF8String, warn, isString,
Promise, MissingDataException, XRefParseException, Stream, Promise, MissingDataException, XRefParseException, Stream,
ChunkedStream, LegacyPromise */ ChunkedStream, createPromiseCapability */
'use strict'; 'use strict';
@ -113,33 +113,26 @@ var Dict = (function DictClosure() {
// Same as get(), but returns a promise and uses fetchIfRefAsync(). // Same as get(), but returns a promise and uses fetchIfRefAsync().
getAsync: function Dict_getAsync(key1, key2, key3) { getAsync: function Dict_getAsync(key1, key2, key3) {
var value; var value;
var promise;
var xref = this.xref; var xref = this.xref;
if (typeof (value = this.map[key1]) !== undefined || key1 in this.map || if (typeof (value = this.map[key1]) !== undefined || key1 in this.map ||
typeof key2 === undefined) { typeof key2 === undefined) {
if (xref) { if (xref) {
return xref.fetchIfRefAsync(value); return xref.fetchIfRefAsync(value);
} }
promise = new LegacyPromise(); return Promise.resolve(value);
promise.resolve(value);
return promise;
} }
if (typeof (value = this.map[key2]) !== undefined || key2 in this.map || if (typeof (value = this.map[key2]) !== undefined || key2 in this.map ||
typeof key3 === undefined) { typeof key3 === undefined) {
if (xref) { if (xref) {
return xref.fetchIfRefAsync(value); return xref.fetchIfRefAsync(value);
} }
promise = new LegacyPromise(); return Promise.resolve(value);
promise.resolve(value);
return promise;
} }
value = this.map[key3] || null; value = this.map[key3] || null;
if (xref) { if (xref) {
return xref.fetchIfRefAsync(value); return xref.fetchIfRefAsync(value);
} }
promise = new LegacyPromise(); return Promise.resolve(value);
promise.resolve(value);
return promise;
}, },
// no dereferencing // no dereferencing
@ -536,7 +529,7 @@ var Catalog = (function CatalogClosure() {
}, },
getPageDict: function Catalog_getPageDict(pageIndex) { getPageDict: function Catalog_getPageDict(pageIndex) {
var promise = new LegacyPromise(); var capability = createPromiseCapability();
var nodesToVisit = [this.catDict.getRaw('Pages')]; var nodesToVisit = [this.catDict.getRaw('Pages')];
var currentPageIndex = 0; var currentPageIndex = 0;
var xref = this.xref; var xref = this.xref;
@ -549,7 +542,7 @@ var Catalog = (function CatalogClosure() {
xref.fetchAsync(currentNode).then(function (obj) { xref.fetchAsync(currentNode).then(function (obj) {
if ((isDict(obj, 'Page') || (isDict(obj) && !obj.has('Kids')))) { if ((isDict(obj, 'Page') || (isDict(obj) && !obj.has('Kids')))) {
if (pageIndex === currentPageIndex) { if (pageIndex === currentPageIndex) {
promise.resolve([obj, currentNode]); capability.resolve([obj, currentNode]);
} else { } else {
currentPageIndex++; currentPageIndex++;
next(); next();
@ -558,7 +551,7 @@ var Catalog = (function CatalogClosure() {
} }
nodesToVisit.push(obj); nodesToVisit.push(obj);
next(); next();
}.bind(this), promise.reject.bind(promise)); }.bind(this), capability.reject.bind(capability));
return; return;
} }
@ -593,10 +586,10 @@ var Catalog = (function CatalogClosure() {
} }
} }
} }
promise.reject('Page index ' + pageIndex + ' not found.'); capability.reject('Page index ' + pageIndex + ' not found.');
} }
next(); next();
return promise; return capability.promise;
}, },
getPageIndex: function Catalog_getPageIndex(ref) { getPageIndex: function Catalog_getPageIndex(ref) {
@ -1254,29 +1247,27 @@ var XRef = (function XRefClosure() {
fetchIfRefAsync: function XRef_fetchIfRefAsync(obj) { fetchIfRefAsync: function XRef_fetchIfRefAsync(obj) {
if (!isRef(obj)) { if (!isRef(obj)) {
var promise = new LegacyPromise(); return Promise.resolve(obj);
promise.resolve(obj);
return promise;
} }
return this.fetchAsync(obj); return this.fetchAsync(obj);
}, },
fetchAsync: function XRef_fetchAsync(ref, suppressEncryption) { fetchAsync: function XRef_fetchAsync(ref, suppressEncryption) {
var promise = new LegacyPromise(); return new Promise(function (resolve, reject) {
var tryFetch = function (promise) { var tryFetch = function () {
try { try {
promise.resolve(this.fetch(ref, suppressEncryption)); resolve(this.fetch(ref, suppressEncryption));
} catch (e) { } catch (e) {
if (e instanceof MissingDataException) { if (e instanceof MissingDataException) {
this.stream.manager.requestRange(e.begin, e.end, tryFetch); this.stream.manager.requestRange(e.begin, e.end, tryFetch);
return; return;
} }
promise.reject(e); reject(e);
} }
}.bind(this, promise); }.bind(this);
tryFetch(); tryFetch();
return promise; }.bind(this));
}, },
getCatalogObj: function XRef_getCatalogObj() { getCatalogObj: function XRef_getCatalogObj() {
return this.root; return this.root;
@ -1481,12 +1472,12 @@ var ObjectLoader = (function() {
ObjectLoader.prototype = { ObjectLoader.prototype = {
load: function ObjectLoader_load() { load: function ObjectLoader_load() {
var keys = this.keys; var keys = this.keys;
this.promise = new LegacyPromise(); this.capability = createPromiseCapability();
// Don't walk the graph if all the data is already loaded. // Don't walk the graph if all the data is already loaded.
if (!(this.xref.stream instanceof ChunkedStream) || if (!(this.xref.stream instanceof ChunkedStream) ||
this.xref.stream.getMissingChunks().length === 0) { this.xref.stream.getMissingChunks().length === 0) {
this.promise.resolve(); this.capability.resolve();
return this.promise; return this.capability.promise;
} }
this.refSet = new RefSet(); this.refSet = new RefSet();
@ -1497,7 +1488,7 @@ var ObjectLoader = (function() {
} }
this.walk(nodesToVisit); this.walk(nodesToVisit);
return this.promise; return this.capability.promise;
}, },
walk: function ObjectLoader_walk(nodesToVisit) { walk: function ObjectLoader_walk(nodesToVisit) {
@ -1564,7 +1555,7 @@ var ObjectLoader = (function() {
} }
// Everything is loaded. // Everything is loaded.
this.refSet = null; this.refSet = null;
this.promise.resolve(); this.capability.resolve();
} }
}; };

View File

@ -17,7 +17,7 @@
/* globals CanvasGraphics, combineUrl, createScratchCanvas, error, /* globals CanvasGraphics, combineUrl, createScratchCanvas, error,
FontLoader, globalScope, info, isArrayBuffer, loadJpegStream, FontLoader, globalScope, info, isArrayBuffer, loadJpegStream,
MessageHandler, PDFJS, Promise, StatTimer, warn, MessageHandler, PDFJS, Promise, StatTimer, warn,
PasswordResponses, Util, loadScript, LegacyPromise, PasswordResponses, Util, loadScript, createPromiseCapability,
FontFace */ FontFace */
'use strict'; 'use strict';
@ -175,7 +175,7 @@ PDFJS.getDocument = function getDocument(source,
pdfDataRangeTransport, pdfDataRangeTransport,
passwordCallback, passwordCallback,
progressCallback) { progressCallback) {
var workerInitializedPromise, workerReadyPromise, transport; var workerInitializedCapability, workerReadyCapability, transport;
if (typeof source === 'string') { if (typeof source === 'string') {
source = { url: source }; source = { url: source };
@ -200,15 +200,16 @@ PDFJS.getDocument = function getDocument(source,
params[key] = source[key]; params[key] = source[key];
} }
workerInitializedPromise = new PDFJS.LegacyPromise(); workerInitializedCapability = createPromiseCapability();
workerReadyPromise = new PDFJS.LegacyPromise(); workerReadyCapability = createPromiseCapability();
transport = new WorkerTransport(workerInitializedPromise, workerReadyPromise, transport = new WorkerTransport(workerInitializedCapability,
pdfDataRangeTransport, progressCallback); workerReadyCapability, pdfDataRangeTransport,
workerInitializedPromise.then(function transportInitialized() { progressCallback);
workerInitializedCapability.promise.then(function transportInitialized() {
transport.passwordCallback = passwordCallback; transport.passwordCallback = passwordCallback;
transport.fetchDocument(params); transport.fetchDocument(params);
}); });
return workerReadyPromise; return workerReadyCapability.promise;
}; };
/** /**
@ -271,10 +272,10 @@ var PDFDocumentProxy = (function PDFDocumentProxyClosure() {
* JavaScript strings in the name tree. * JavaScript strings in the name tree.
*/ */
getJavaScript: function PDFDocumentProxy_getJavaScript() { getJavaScript: function PDFDocumentProxy_getJavaScript() {
var promise = new PDFJS.LegacyPromise(); return new Promise(function (resolve) {
var js = this.pdfInfo.javaScript; var js = this.pdfInfo.javaScript;
promise.resolve(js); resolve(js);
return promise; }.bind(this));
}, },
/** /**
* @return {Promise} A promise that is resolved with an {Array} that is a * @return {Promise} A promise that is resolved with an {Array} that is a
@ -292,10 +293,10 @@ var PDFDocumentProxy = (function PDFDocumentProxyClosure() {
* ]. * ].
*/ */
getOutline: function PDFDocumentProxy_getOutline() { getOutline: function PDFDocumentProxy_getOutline() {
var promise = new PDFJS.LegacyPromise(); return new Promise(function (resolve) {
var outline = this.pdfInfo.outline; var outline = this.pdfInfo.outline;
promise.resolve(outline); resolve(outline);
return promise; }.bind(this));
}, },
/** /**
* @return {Promise} A promise that is resolved with an {Object} that has * @return {Promise} A promise that is resolved with an {Object} that has
@ -304,23 +305,23 @@ var PDFDocumentProxy = (function PDFDocumentProxyClosure() {
* {Metadata} object with information from the metadata section of the PDF. * {Metadata} object with information from the metadata section of the PDF.
*/ */
getMetadata: function PDFDocumentProxy_getMetadata() { getMetadata: function PDFDocumentProxy_getMetadata() {
var promise = new PDFJS.LegacyPromise(); return new Promise(function (resolve) {
var info = this.pdfInfo.info; var info = this.pdfInfo.info;
var metadata = this.pdfInfo.metadata; var metadata = this.pdfInfo.metadata;
promise.resolve({ resolve({
info: info, info: info,
metadata: (metadata ? new PDFJS.Metadata(metadata) : null) metadata: (metadata ? new PDFJS.Metadata(metadata) : null)
}); });
return promise; }.bind(this));
}, },
/** /**
* @return {Promise} A promise that is resolved with a TypedArray that has * @return {Promise} A promise that is resolved with a TypedArray that has
* the raw data from the PDF. * the raw data from the PDF.
*/ */
getData: function PDFDocumentProxy_getData() { getData: function PDFDocumentProxy_getData() {
var promise = new PDFJS.LegacyPromise(); var capability = createPromiseCapability();
this.transport.getData(promise); this.transport.getData(capability);
return promise; return capability.promise;
}, },
/** /**
* @return {Promise} A promise that is resolved when the document's data * @return {Promise} A promise that is resolved when the document's data
@ -328,7 +329,7 @@ var PDFDocumentProxy = (function PDFDocumentProxyClosure() {
* property that indicates size of the PDF data in bytes. * property that indicates size of the PDF data in bytes.
*/ */
getDownloadInfo: function PDFDocumentProxy_getDownloadInfo() { getDownloadInfo: function PDFDocumentProxy_getDownloadInfo() {
return this.transport.downloadInfoPromise; return this.transport.downloadInfoCapability.promise;
}, },
/** /**
* Cleans up resources allocated by the document, e.g. created @font-face. * Cleans up resources allocated by the document, e.g. created @font-face.
@ -455,14 +456,14 @@ var PDFPageProxy = (function PDFPageProxyClosure() {
* annotation objects. * annotation objects.
*/ */
getAnnotations: function PDFPageProxy_getAnnotations() { getAnnotations: function PDFPageProxy_getAnnotations() {
if (this.annotationsPromise) { if (this.annotationsCapability) {
return this.annotationsPromise; return this.annotationsCapability.promise;
} }
var promise = new PDFJS.LegacyPromise(); var capability = createPromiseCapability();
this.annotationsPromise = promise; this.annotationsCapability = capability;
this.transport.getAnnotations(this.pageInfo.pageIndex); this.transport.getAnnotations(this.pageInfo.pageIndex);
return promise; return capability.promise;
}, },
/** /**
* Begins the process of rendering a page to the desired context. * Begins the process of rendering a page to the desired context.
@ -486,11 +487,11 @@ var PDFPageProxy = (function PDFPageProxyClosure() {
} }
var intentState = this.intentStates[renderingIntent]; var intentState = this.intentStates[renderingIntent];
// If there is no displayReadyPromise yet, then the operatorList was never // If there's no displayReadyCapability yet, then the operatorList
// requested before. Make the request and create the promise. // was never requested before. Make the request and create the promise.
if (!intentState.displayReadyPromise) { if (!intentState.displayReadyCapability) {
intentState.receivingOperatorList = true; intentState.receivingOperatorList = true;
intentState.displayReadyPromise = new LegacyPromise(); intentState.displayReadyCapability = createPromiseCapability();
intentState.operatorList = { intentState.operatorList = {
fnArray: [], fnArray: [],
argsArray: [], argsArray: [],
@ -516,7 +517,7 @@ var PDFPageProxy = (function PDFPageProxyClosure() {
var renderTask = new RenderTask(internalRenderTask); var renderTask = new RenderTask(internalRenderTask);
var self = this; var self = this;
intentState.displayReadyPromise.then( intentState.displayReadyCapability.promise.then(
function pageDisplayReadyPromise(transparency) { function pageDisplayReadyPromise(transparency) {
if (self.pendingDestroy) { if (self.pendingDestroy) {
complete(); complete();
@ -543,9 +544,9 @@ var PDFPageProxy = (function PDFPageProxyClosure() {
self._tryDestroy(); self._tryDestroy();
if (error) { if (error) {
renderTask.promise.reject(error); internalRenderTask.capability.reject(error);
} else { } else {
renderTask.promise.resolve(); internalRenderTask.capability.resolve();
} }
stats.timeEnd('Rendering'); stats.timeEnd('Rendering');
stats.timeEnd('Overall'); stats.timeEnd('Overall');
@ -558,15 +559,15 @@ var PDFPageProxy = (function PDFPageProxyClosure() {
* object that represent the page text content. * object that represent the page text content.
*/ */
getTextContent: function PDFPageProxy_getTextContent() { getTextContent: function PDFPageProxy_getTextContent() {
var promise = new PDFJS.LegacyPromise(); return new Promise(function (resolve) {
this.transport.messageHandler.send('GetTextContent', { this.transport.messageHandler.send('GetTextContent', {
pageIndex: this.pageNumber - 1 pageIndex: this.pageNumber - 1
}, },
function textContentCallback(textContent) { function textContentCallback(textContent) {
promise.resolve(textContent); resolve(textContent);
} }
); );
return promise; }.bind(this));
}, },
/** /**
* Destroys resources allocated by the page. * Destroys resources allocated by the page.
@ -603,7 +604,7 @@ var PDFPageProxy = (function PDFPageProxyClosure() {
_startRenderPage: function PDFPageProxy_startRenderPage(transparency, _startRenderPage: function PDFPageProxy_startRenderPage(transparency,
intent) { intent) {
var intentState = this.intentStates[intent]; var intentState = this.intentStates[intent];
intentState.displayReadyPromise.resolve(transparency); intentState.displayReadyCapability.resolve(transparency);
}, },
/** /**
* For internal use only. * For internal use only.
@ -640,17 +641,17 @@ var PDFPageProxy = (function PDFPageProxyClosure() {
* @ignore * @ignore
*/ */
var WorkerTransport = (function WorkerTransportClosure() { var WorkerTransport = (function WorkerTransportClosure() {
function WorkerTransport(workerInitializedPromise, workerReadyPromise, function WorkerTransport(workerInitializedCapability, workerReadyCapability,
pdfDataRangeTransport, progressCallback) { pdfDataRangeTransport, progressCallback) {
this.pdfDataRangeTransport = pdfDataRangeTransport; this.pdfDataRangeTransport = pdfDataRangeTransport;
this.workerReadyPromise = workerReadyPromise; this.workerReadyCapability = workerReadyCapability;
this.progressCallback = progressCallback; this.progressCallback = progressCallback;
this.commonObjs = new PDFObjects(); this.commonObjs = new PDFObjects();
this.pageCache = []; this.pageCache = [];
this.pagePromises = []; this.pageCapabilities = [];
this.downloadInfoPromise = new PDFJS.LegacyPromise(); this.downloadInfoCapability = createPromiseCapability();
this.passwordCallback = null; this.passwordCallback = null;
// If worker support isn't disabled explicit and the browser has worker // If worker support isn't disabled explicit and the browser has worker
@ -680,12 +681,12 @@ var WorkerTransport = (function WorkerTransportClosure() {
PDFJS.postMessageTransfers = false; PDFJS.postMessageTransfers = false;
} }
this.setupMessageHandler(messageHandler); this.setupMessageHandler(messageHandler);
workerInitializedPromise.resolve(); workerInitializedCapability.resolve();
} else { } else {
globalScope.PDFJS.disableWorker = true; globalScope.PDFJS.disableWorker = true;
this.loadFakeWorkerFiles().then(function() { this.loadFakeWorkerFiles().then(function() {
this.setupFakeWorker(); this.setupFakeWorker();
workerInitializedPromise.resolve(); workerInitializedCapability.resolve();
}.bind(this)); }.bind(this));
} }
}.bind(this)); }.bind(this));
@ -711,13 +712,13 @@ var WorkerTransport = (function WorkerTransportClosure() {
globalScope.PDFJS.disableWorker = true; globalScope.PDFJS.disableWorker = true;
this.loadFakeWorkerFiles().then(function() { this.loadFakeWorkerFiles().then(function() {
this.setupFakeWorker(); this.setupFakeWorker();
workerInitializedPromise.resolve(); workerInitializedCapability.resolve();
}.bind(this)); }.bind(this));
} }
WorkerTransport.prototype = { WorkerTransport.prototype = {
destroy: function WorkerTransport_destroy() { destroy: function WorkerTransport_destroy() {
this.pageCache = []; this.pageCache = [];
this.pagePromises = []; this.pageCapabilities = [];
var self = this; var self = this;
this.messageHandler.send('Terminate', null, function () { this.messageHandler.send('Terminate', null, function () {
FontLoader.clear(); FontLoader.clear();
@ -728,8 +729,8 @@ var WorkerTransport = (function WorkerTransportClosure() {
}, },
loadFakeWorkerFiles: function WorkerTransport_loadFakeWorkerFiles() { loadFakeWorkerFiles: function WorkerTransport_loadFakeWorkerFiles() {
if (!PDFJS.fakeWorkerFilesLoadedPromise) { if (!PDFJS.fakeWorkerFilesLoadedCapability) {
PDFJS.fakeWorkerFilesLoadedPromise = new LegacyPromise(); PDFJS.fakeWorkerFilesLoadedCapability = createPromiseCapability();
// In the developer build load worker_loader which in turn loads all the // In the developer build load worker_loader which in turn loads all the
// other files and resolves the promise. In production only the // other files and resolves the promise. In production only the
// pdf.worker.js file is needed. // pdf.worker.js file is needed.
@ -737,15 +738,15 @@ var WorkerTransport = (function WorkerTransportClosure() {
Util.loadScript(PDFJS.workerSrc); Util.loadScript(PDFJS.workerSrc);
//#endif //#endif
//#if PRODUCTION && SINGLE_FILE //#if PRODUCTION && SINGLE_FILE
// PDFJS.fakeWorkerFilesLoadedPromise.resolve(); // PDFJS.fakeWorkerFilesLoadedCapability.resolve();
//#endif //#endif
//#if PRODUCTION && !SINGLE_FILE //#if PRODUCTION && !SINGLE_FILE
// Util.loadScript(PDFJS.workerSrc, function() { // Util.loadScript(PDFJS.workerSrc, function() {
// PDFJS.fakeWorkerFilesLoadedPromise.resolve(); // PDFJS.fakeWorkerFilesLoadedCapability.resolve();
// }); // });
//#endif //#endif
} }
return PDFJS.fakeWorkerFilesLoadedPromise; return PDFJS.fakeWorkerFilesLoadedCapability.promise;
}, },
setupFakeWorker: function WorkerTransport_setupFakeWorker() { setupFakeWorker: function WorkerTransport_setupFakeWorker() {
@ -800,7 +801,7 @@ var WorkerTransport = (function WorkerTransportClosure() {
this.numPages = data.pdfInfo.numPages; this.numPages = data.pdfInfo.numPages;
var pdfDocument = new PDFDocumentProxy(pdfInfo, this); var pdfDocument = new PDFDocumentProxy(pdfInfo, this);
this.pdfDocument = pdfDocument; this.pdfDocument = pdfDocument;
this.workerReadyPromise.resolve(pdfDocument); this.workerReadyCapability.resolve(pdfDocument);
}, this); }, this);
messageHandler.on('NeedPassword', function transportPassword(data) { messageHandler.on('NeedPassword', function transportPassword(data) {
@ -808,7 +809,8 @@ var WorkerTransport = (function WorkerTransportClosure() {
return this.passwordCallback(updatePassword, return this.passwordCallback(updatePassword,
PasswordResponses.NEED_PASSWORD); PasswordResponses.NEED_PASSWORD);
} }
this.workerReadyPromise.reject(data.exception.message, data.exception); this.workerReadyCapability.reject(data.exception.message,
data.exception);
}, this); }, this);
messageHandler.on('IncorrectPassword', function transportBadPass(data) { messageHandler.on('IncorrectPassword', function transportBadPass(data) {
@ -816,36 +818,39 @@ var WorkerTransport = (function WorkerTransportClosure() {
return this.passwordCallback(updatePassword, return this.passwordCallback(updatePassword,
PasswordResponses.INCORRECT_PASSWORD); PasswordResponses.INCORRECT_PASSWORD);
} }
this.workerReadyPromise.reject(data.exception.message, data.exception); this.workerReadyCapability.reject(data.exception.message,
data.exception);
}, this); }, this);
messageHandler.on('InvalidPDF', function transportInvalidPDF(data) { messageHandler.on('InvalidPDF', function transportInvalidPDF(data) {
this.workerReadyPromise.reject(data.exception.name, data.exception); this.workerReadyCapability.reject(data.exception.name, data.exception);
}, this); }, this);
messageHandler.on('MissingPDF', function transportMissingPDF(data) { messageHandler.on('MissingPDF', function transportMissingPDF(data) {
this.workerReadyPromise.reject(data.exception.message, data.exception); this.workerReadyCapability.reject(data.exception.message,
data.exception);
}, this); }, this);
messageHandler.on('UnknownError', function transportUnknownError(data) { messageHandler.on('UnknownError', function transportUnknownError(data) {
this.workerReadyPromise.reject(data.exception.message, data.exception); this.workerReadyCapability.reject(data.exception.message,
data.exception);
}, this); }, this);
messageHandler.on('DataLoaded', function transportPage(data) { messageHandler.on('DataLoaded', function transportPage(data) {
this.downloadInfoPromise.resolve(data); this.downloadInfoCapability.resolve(data);
}, this); }, this);
messageHandler.on('GetPage', function transportPage(data) { messageHandler.on('GetPage', function transportPage(data) {
var pageInfo = data.pageInfo; var pageInfo = data.pageInfo;
var page = new PDFPageProxy(pageInfo, this); var page = new PDFPageProxy(pageInfo, this);
this.pageCache[pageInfo.pageIndex] = page; this.pageCache[pageInfo.pageIndex] = page;
var promise = this.pagePromises[pageInfo.pageIndex]; var promise = this.pageCapabilities[pageInfo.pageIndex];
promise.resolve(page); promise.resolve(page);
}, this); }, this);
messageHandler.on('GetAnnotations', function transportAnnotations(data) { messageHandler.on('GetAnnotations', function transportAnnotations(data) {
var annotations = data.annotations; var annotations = data.annotations;
var promise = this.pageCache[data.pageIndex].annotationsPromise; var promise = this.pageCache[data.pageIndex].annotationsCapability;
promise.resolve(annotations); promise.resolve(annotations);
}, this); }, this);
@ -939,14 +944,14 @@ var WorkerTransport = (function WorkerTransportClosure() {
}, this); }, this);
messageHandler.on('DocError', function transportDocError(data) { messageHandler.on('DocError', function transportDocError(data) {
this.workerReadyPromise.reject(data); this.workerReadyCapability.reject(data);
}, this); }, this);
messageHandler.on('PageError', function transportError(data, intent) { messageHandler.on('PageError', function transportError(data, intent) {
var page = this.pageCache[data.pageNum - 1]; var page = this.pageCache[data.pageNum - 1];
var intentState = page.intentStates[intent]; var intentState = page.intentStates[intent];
if (intentState.displayReadyPromise) { if (intentState.displayReadyCapability.promise) {
intentState.displayReadyPromise.reject(data.error); intentState.displayReadyCapability.reject(data.error);
} else { } else {
error(data.error); error(data.error);
} }
@ -1004,38 +1009,36 @@ var WorkerTransport = (function WorkerTransportClosure() {
}); });
}, },
getData: function WorkerTransport_getData(promise) { getData: function WorkerTransport_getData(capability) {
this.messageHandler.send('GetData', null, function(data) { this.messageHandler.send('GetData', null, function(data) {
promise.resolve(data); capability.resolve(data);
}); });
}, },
getPage: function WorkerTransport_getPage(pageNumber, promise) { getPage: function WorkerTransport_getPage(pageNumber, capability) {
if (pageNumber <= 0 || pageNumber > this.numPages || if (pageNumber <= 0 || pageNumber > this.numPages ||
(pageNumber|0) !== pageNumber) { (pageNumber|0) !== pageNumber) {
var pagePromise = new PDFJS.LegacyPromise(); return new Promise.reject(new Error('Invalid page request'));
pagePromise.reject(new Error('Invalid page request'));
return pagePromise;
} }
var pageIndex = pageNumber - 1; var pageIndex = pageNumber - 1;
if (pageIndex in this.pagePromises) { if (pageIndex in this.pageCapabilities) {
return this.pagePromises[pageIndex]; return this.pageCapabilities[pageIndex].promise;
} }
promise = new PDFJS.LegacyPromise(); capability = createPromiseCapability();
this.pagePromises[pageIndex] = promise; this.pageCapabilities[pageIndex] = capability;
this.messageHandler.send('GetPageRequest', { pageIndex: pageIndex }); this.messageHandler.send('GetPageRequest', { pageIndex: pageIndex });
return promise; return capability.promise;
}, },
getPageIndex: function WorkerTransport_getPageIndexByRef(ref) { getPageIndex: function WorkerTransport_getPageIndexByRef(ref) {
var promise = new PDFJS.LegacyPromise(); return new Promise(function (resolve) {
this.messageHandler.send('GetPageIndex', { ref: ref }, this.messageHandler.send('GetPageIndex', { ref: ref },
function (pageIndex) { function (pageIndex) {
promise.resolve(pageIndex); resolve(pageIndex);
} }
); );
return promise; }.bind(this));
}, },
getAnnotations: function WorkerTransport_getAnnotations(pageIndex) { getAnnotations: function WorkerTransport_getAnnotations(pageIndex) {
@ -1044,23 +1047,23 @@ var WorkerTransport = (function WorkerTransportClosure() {
}, },
getDestinations: function WorkerTransport_getDestinations() { getDestinations: function WorkerTransport_getDestinations() {
var promise = new PDFJS.LegacyPromise(); return new Promise(function (resolve) {
this.messageHandler.send('GetDestinations', null, this.messageHandler.send('GetDestinations', null,
function transportDestinations(destinations) { function transportDestinations(destinations) {
promise.resolve(destinations); resolve(destinations);
} }
); );
return promise; }.bind(this));
}, },
getAttachments: function WorkerTransport_getAttachments() { getAttachments: function WorkerTransport_getAttachments() {
var promise = new PDFJS.LegacyPromise(); return new Promise(function (resolve) {
this.messageHandler.send('GetAttachments', null, this.messageHandler.send('GetAttachments', null,
function transportAttachments(attachments) { function transportAttachments(attachments) {
promise.resolve(attachments); resolve(attachments);
} }
); );
return promise; }.bind(this));
}, },
startCleanup: function WorkerTransport_startCleanup() { startCleanup: function WorkerTransport_startCleanup() {
@ -1105,7 +1108,7 @@ var PDFObjects = (function PDFObjectsClosure() {
} }
var obj = { var obj = {
promise: new LegacyPromise(), capability: createPromiseCapability(),
data: null, data: null,
resolved: false resolved: false
}; };
@ -1127,7 +1130,7 @@ var PDFObjects = (function PDFObjectsClosure() {
// If there is a callback, then the get can be async and the object is // If there is a callback, then the get can be async and the object is
// not required to be resolved right now // not required to be resolved right now
if (callback) { if (callback) {
this.ensureObj(objId).promise.then(callback); this.ensureObj(objId).capability.promise.then(callback);
return null; return null;
} }
@ -1152,7 +1155,7 @@ var PDFObjects = (function PDFObjectsClosure() {
obj.resolved = true; obj.resolved = true;
obj.data = data; obj.data = data;
obj.promise.resolve(data); obj.capability.resolve(data);
}, },
isResolved: function PDFObjects_isResolved(objId) { isResolved: function PDFObjects_isResolved(objId) {
@ -1199,7 +1202,7 @@ var RenderTask = (function RenderTaskClosure() {
* Promise for rendering task completion. * Promise for rendering task completion.
* @type {Promise} * @type {Promise}
*/ */
this.promise = new PDFJS.LegacyPromise(); this.promise = this.internalRenderTask.capability.promise;
} }
RenderTask.prototype = /** @lends RenderTask.prototype */ { RenderTask.prototype = /** @lends RenderTask.prototype */ {
@ -1210,7 +1213,6 @@ var RenderTask = (function RenderTaskClosure() {
*/ */
cancel: function RenderTask_cancel() { cancel: function RenderTask_cancel() {
this.internalRenderTask.cancel(); this.internalRenderTask.cancel();
this.promise.reject(new Error('Rendering is cancelled'));
}, },
/** /**
@ -1248,6 +1250,7 @@ var InternalRenderTask = (function InternalRenderTaskClosure() {
this.graphicsReadyCallback = null; this.graphicsReadyCallback = null;
this.graphicsReady = false; this.graphicsReady = false;
this.cancelled = false; this.cancelled = false;
this.capability = createPromiseCapability();
} }
InternalRenderTask.prototype = { InternalRenderTask.prototype = {
@ -1280,6 +1283,7 @@ var InternalRenderTask = (function InternalRenderTaskClosure() {
cancel: function InternalRenderTask_cancel() { cancel: function InternalRenderTask_cancel() {
this.running = false; this.running = false;
this.cancelled = true; this.cancelled = true;
this.capability.reject(new Error('Rendering is cancelled'));
this.callback('cancelled'); this.callback('cancelled');
}, },