chore: add missing await to floating promises (#5813)

This commit is contained in:
Yury Semikhatsky 2021-03-22 09:59:39 -07:00 committed by GitHub
parent be9fa743ca
commit 67c29e8155
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
17 changed files with 46 additions and 43 deletions

View File

@ -39,7 +39,7 @@ program
commandWithOpenOptions('open [url]', 'open page in browser specified via -b, --browser', []) commandWithOpenOptions('open [url]', 'open page in browser specified via -b, --browser', [])
.action(function(url, command) { .action(function(url, command) {
open(command, url, language()); open(command, url, language()).catch(logErrorAndExit);
}) })
.on('--help', function() { .on('--help', function() {
console.log(''); console.log('');
@ -54,7 +54,7 @@ commandWithOpenOptions('codegen [url]', 'open page and generate code for user ac
['-o, --output <file name>', 'saves the generated script to a file'], ['-o, --output <file name>', 'saves the generated script to a file'],
['--target <language>', `language to use, one of javascript, python, python-async, csharp`, language()], ['--target <language>', `language to use, one of javascript, python, python-async, csharp`, language()],
]).action(function(url, command) { ]).action(function(url, command) {
codegen(command, url, command.target, command.output); codegen(command, url, command.target, command.output).catch(logErrorAndExit);
}).on('--help', function() { }).on('--help', function() {
console.log(''); console.log('');
console.log('Examples:'); console.log('Examples:');
@ -122,7 +122,7 @@ const browsers = [
for (const {alias, name, type} of browsers) { for (const {alias, name, type} of browsers) {
commandWithOpenOptions(`${alias} [url]`, `open page in ${name}`, []) commandWithOpenOptions(`${alias} [url]`, `open page in ${name}`, [])
.action(function(url, command) { .action(function(url, command) {
open({ ...command, browser: type }, url, command.target); open({ ...command, browser: type }, url, command.target).catch(logErrorAndExit);
}).on('--help', function() { }).on('--help', function() {
console.log(''); console.log('');
console.log('Examples:'); console.log('Examples:');
@ -137,7 +137,7 @@ commandWithOpenOptions('screenshot <url> <filename>', 'capture a page screenshot
['--wait-for-timeout <timeout>', 'wait for timeout in milliseconds before taking a screenshot'], ['--wait-for-timeout <timeout>', 'wait for timeout in milliseconds before taking a screenshot'],
['--full-page', 'whether to take a full page screenshot (entire scrollable area)'], ['--full-page', 'whether to take a full page screenshot (entire scrollable area)'],
]).action(function(url, filename, command) { ]).action(function(url, filename, command) {
screenshot(command, command, url, filename); screenshot(command, command, url, filename).catch(logErrorAndExit);
}).on('--help', function() { }).on('--help', function() {
console.log(''); console.log('');
console.log('Examples:'); console.log('Examples:');
@ -150,7 +150,7 @@ commandWithOpenOptions('pdf <url> <filename>', 'save page as pdf',
['--wait-for-selector <selector>', 'wait for given selector before saving as pdf'], ['--wait-for-selector <selector>', 'wait for given selector before saving as pdf'],
['--wait-for-timeout <timeout>', 'wait for given timeout in milliseconds before saving as pdf'], ['--wait-for-timeout <timeout>', 'wait for given timeout in milliseconds before saving as pdf'],
]).action(function(url, filename, command) { ]).action(function(url, filename, command) {
pdf(command, command, url, filename); pdf(command, command, url, filename).catch(logErrorAndExit);
}).on('--help', function() { }).on('--help', function() {
console.log(''); console.log('');
console.log('Examples:'); console.log('Examples:');
@ -164,7 +164,7 @@ if (process.env.PWTRACE) {
.option('--resources <dir>', 'load resources from shared folder') .option('--resources <dir>', 'load resources from shared folder')
.description('Show trace viewer') .description('Show trace viewer')
.action(function(trace, command) { .action(function(trace, command) {
showTraceViewer(trace, command.resources); showTraceViewer(trace, command.resources).catch(logErrorAndExit);
}).on('--help', function() { }).on('--help', function() {
console.log(''); console.log('');
console.log('Examples:'); console.log('Examples:');
@ -179,7 +179,7 @@ if (process.argv[2] === 'run-driver')
else if (process.argv[2] === 'print-api-json') else if (process.argv[2] === 'print-api-json')
printApiJson(); printApiJson();
else if (process.argv[2] === 'launch-server') else if (process.argv[2] === 'launch-server')
launchBrowserServer(process.argv[3], process.argv[4]); launchBrowserServer(process.argv[3], process.argv[4]).catch(logErrorAndExit);
else else
program.parse(process.argv); program.parse(process.argv);
@ -446,6 +446,11 @@ function validateOptions(options: Options) {
} }
} }
function logErrorAndExit(e: Error) {
console.error(e);
process.exit(1);
}
function language(): string { function language(): string {
return process.env.PW_CLI_TARGET_LANG || 'javascript'; return process.env.PW_CLI_TARGET_LANG || 'javascript';
} }

View File

@ -87,7 +87,7 @@ export class BrowserContext extends ChannelOwner<channels.BrowserContextChannel,
const func = this._bindings.get(bindingCall._initializer.name); const func = this._bindings.get(bindingCall._initializer.name);
if (!func) if (!func)
return; return;
bindingCall.call(func); await bindingCall.call(func);
} }
setDefaultNavigationTimeout(timeout: number) { setDefaultNavigationTimeout(timeout: number) {
@ -238,7 +238,7 @@ export class BrowserContext extends ChannelOwner<channels.BrowserContextChannel,
}); });
} }
async _onClose() { _onClose() {
if (this._browser) if (this._browser)
this._browser._contexts.delete(this); this._browser._contexts.delete(this);
this.emit(Events.BrowserContext.Close, this); this.emit(Events.BrowserContext.Close, this);

View File

@ -186,10 +186,10 @@ export class Page extends ChannelOwner<channels.PageChannel, channels.PageInitia
async _onBinding(bindingCall: BindingCall) { async _onBinding(bindingCall: BindingCall) {
const func = this._bindings.get(bindingCall._initializer.name); const func = this._bindings.get(bindingCall._initializer.name);
if (func) { if (func) {
bindingCall.call(func); await bindingCall.call(func);
return; return;
} }
this._browserContext._onBinding(bindingCall); await this._browserContext._onBinding(bindingCall);
} }
_onWorker(worker: Worker): void { _onWorker(worker: Worker): void {

View File

@ -184,7 +184,7 @@ export class AndroidSocketDispatcher extends Dispatcher<SocketBackend, channels.
} }
async close(params: channels.AndroidSocketCloseParams, metadata: CallMetadata): Promise<void> { async close(params: channels.AndroidSocketCloseParams, metadata: CallMetadata): Promise<void> {
await this._object.close(); this._object.close();
} }
} }

View File

@ -48,11 +48,11 @@ export class PlaywrightServer {
ws.on('message', message => dispatcherConnection.dispatch(JSON.parse(message.toString()))); ws.on('message', message => dispatcherConnection.dispatch(JSON.parse(message.toString())));
ws.on('close', () => { ws.on('close', () => {
debugLog('Client closed'); debugLog('Client closed');
this._onDisconnect(); this._onDisconnect().catch(debugLog);
}); });
ws.on('error', error => { ws.on('error', error => {
debugLog('Client error ' + error); debugLog('Client error ' + error);
this._onDisconnect(); this._onDisconnect().catch(debugLog);
}); });
dispatcherConnection.onmessage = message => ws.send(JSON.stringify(message)); dispatcherConnection.onmessage = message => ws.send(JSON.stringify(message));
new PlaywrightDispatcher(dispatcherConnection.rootDispatcher(), createPlaywright()); new PlaywrightDispatcher(dispatcherConnection.rootDispatcher(), createPlaywright());

View File

@ -43,7 +43,7 @@ export interface Backend {
export interface DeviceBackend { export interface DeviceBackend {
serial: string; serial: string;
status: string; status: string;
close(): Promise<void>; close(): void;
init(): Promise<void>; init(): Promise<void>;
runCommand(command: string): Promise<Buffer>; runCommand(command: string): Promise<Buffer>;
open(command: string): Promise<SocketBackend>; open(command: string): Promise<SocketBackend>;
@ -51,7 +51,7 @@ export interface DeviceBackend {
export interface SocketBackend extends EventEmitter { export interface SocketBackend extends EventEmitter {
write(data: Buffer): Promise<void>; write(data: Buffer): Promise<void>;
close(): Promise<void>; close(): void;
} }
export class Android extends SdkObject { export class Android extends SdkObject {
@ -176,7 +176,7 @@ export class AndroidDevice extends SdkObject {
await this.installApk(await readFileAsync(require.resolve(`../../../bin/${file}`))); await this.installApk(await readFileAsync(require.resolve(`../../../bin/${file}`)));
debug('pw:android')('Starting the new driver'); debug('pw:android')('Starting the new driver');
this.shell('am instrument -w com.microsoft.playwright.androiddriver.test/androidx.test.runner.AndroidJUnitRunner'); this.shell('am instrument -w com.microsoft.playwright.androiddriver.test/androidx.test.runner.AndroidJUnitRunner').catch(e => debug('pw:android')(e));
const socket = await this._waitForLocalAbstract('playwright_android_driver_socket'); const socket = await this._waitForLocalAbstract('playwright_android_driver_socket');
const transport = new Transport(socket, socket, socket, 'be'); const transport = new Transport(socket, socket, socket, 'be');
transport.onmessage = message => { transport.onmessage = message => {
@ -301,7 +301,7 @@ export class AndroidDevice extends SdkObject {
await installSocket.write(content); await installSocket.write(content);
const success = await new Promise(f => installSocket.on('data', f)); const success = await new Promise(f => installSocket.on('data', f));
debug('pw:android')('Written driver bytes: ' + success); debug('pw:android')('Written driver bytes: ' + success);
await installSocket.close(); installSocket.close();
} }
async push(content: Buffer, path: string, mode = 0o644): Promise<void> { async push(content: Buffer, path: string, mode = 0o644): Promise<void> {
@ -325,7 +325,7 @@ export class AndroidDevice extends SdkObject {
const code = result.slice(0, 4).toString(); const code = result.slice(0, 4).toString();
if (code !== 'OKAY') if (code !== 'OKAY')
throw new Error('Could not push: ' + code); throw new Error('Could not push: ' + code);
await socket.close(); socket.close();
} }
private async _refreshWebViews() { private async _refreshWebViews() {
@ -420,7 +420,7 @@ Sec-WebSocket-Version: 13\r
} }
async close() { async close() {
await this._socket!.close(); this._socket!.close();
} }
} }

View File

@ -75,7 +75,7 @@ async function runCommand(command: string, serial?: string): Promise<Buffer> {
} else { } else {
commandOutput = await socket.readAll(); commandOutput = await socket.readAll();
} }
await socket.close(); socket.close();
return commandOutput; return commandOutput;
} }
@ -138,7 +138,7 @@ class BufferedSocketWrapper extends EventEmitter implements SocketBackend {
await new Promise(f => this._socket.write(data, f)); await new Promise(f => this._socket.write(data, f));
} }
async close() { close() {
if (this._isClosed) if (this._isClosed)
return; return;
debug('pw:adb')('Close ' + this._command); debug('pw:adb')('Close ' + this._command);

View File

@ -33,7 +33,7 @@ export class CRDevTools {
this._savePromise = Promise.resolve(); this._savePromise = Promise.resolve();
} }
async install(session: CRSession) { install(session: CRSession) {
session.on('Runtime.bindingCalled', async event => { session.on('Runtime.bindingCalled', async event => {
if (event.name !== kBindingName) if (event.name !== kBindingName)
return; return;
@ -66,7 +66,7 @@ export class CRDevTools {
contextId: event.executionContextId contextId: event.executionContextId
}).catch(e => null); }).catch(e => null);
}); });
await Promise.all([ Promise.all([
session.send('Runtime.enable'), session.send('Runtime.enable'),
session.send('Runtime.addBinding', { name: kBindingName }), session.send('Runtime.addBinding', { name: kBindingName }),
session.send('Page.enable'), session.send('Page.enable'),

View File

@ -646,11 +646,10 @@ class FrameSession {
session.once('Runtime.executionContextCreated', async event => { session.once('Runtime.executionContextCreated', async event => {
worker._createExecutionContext(new CRExecutionContext(session, event.context)); worker._createExecutionContext(new CRExecutionContext(session, event.context));
}); });
Promise.all([ // This might fail if the target is closed before we initialize.
session._sendMayFail('Runtime.enable'), session._sendMayFail('Runtime.enable');
session._sendMayFail('Network.enable'), session._sendMayFail('Network.enable');
session._sendMayFail('Runtime.runIfWaitingForDebugger'), session._sendMayFail('Runtime.runIfWaitingForDebugger');
]); // This might fail if the target is closed before we initialize.
session.on('Runtime.consoleAPICalled', event => { session.on('Runtime.consoleAPICalled', event => {
const args = event.args.map(o => worker._existingExecutionContext!.createHandle(o)); const args = event.args.map(o => worker._existingExecutionContext!.createHandle(o));
this._page._addConsoleMessage(event.type, args, toConsoleMessageLocation(event.stackTrace)); this._page._addConsoleMessage(event.type, args, toConsoleMessageLocation(event.stackTrace));

View File

@ -83,7 +83,7 @@ export class Download {
throw new Error('Download not found on disk. Check download.failure() for details.'); throw new Error('Download not found on disk. Check download.failure() for details.');
if (this._finished) { if (this._finished) {
saveCallback(path.join(this._downloadsPath, this._uuid)); saveCallback(path.join(this._downloadsPath, this._uuid)).catch(e => {});
return; return;
} }
this._saveCallbacks.push(saveCallback); this._saveCallbacks.push(saveCallback);
@ -117,7 +117,7 @@ export class Download {
const fileName = path.join(this._downloadsPath, this._uuid); const fileName = path.join(this._downloadsPath, this._uuid);
await util.promisify(fs.unlink)(fileName).catch(e => {}); await util.promisify(fs.unlink)(fileName).catch(e => {});
} }
this._reportFinished('Download deleted upon browser context closure.'); await this._reportFinished('Download deleted upon browser context closure.');
} }
async _reportFinished(error?: string) { async _reportFinished(error?: string) {
@ -128,7 +128,7 @@ export class Download {
if (error) { if (error) {
for (const callback of this._saveCallbacks) for (const callback of this._saveCallbacks)
callback('', error); await callback('', error);
} else { } else {
const fullPath = path.join(this._downloadsPath, this._uuid); const fullPath = path.join(this._downloadsPath, this._uuid);
for (const callback of this._saveCallbacks) for (const callback of this._saveCallbacks)

View File

@ -90,7 +90,7 @@ export class FFExecutionContext implements js.ExecutionContextDelegate {
await this._session.send('Runtime.disposeObject', { await this._session.send('Runtime.disposeObject', {
executionContextId: this._executionContextId, executionContextId: this._executionContextId,
objectId: handle._objectId, objectId: handle._objectId,
}).catch(error => {}); });
} }
} }

View File

@ -232,14 +232,14 @@ export class FFPage implements PageDelegate {
const context = this._contextIdToContext.get(event.executionContextId)!; const context = this._contextIdToContext.get(event.executionContextId)!;
const pageOrError = await this.pageOrError(); const pageOrError = await this.pageOrError();
if (!(pageOrError instanceof Error)) if (!(pageOrError instanceof Error))
this._page._onBindingCalled(event.payload, context); await this._page._onBindingCalled(event.payload, context);
} }
async _onFileChooserOpened(payload: Protocol.Page.fileChooserOpenedPayload) { async _onFileChooserOpened(payload: Protocol.Page.fileChooserOpenedPayload) {
const {executionContextId, element} = payload; const {executionContextId, element} = payload;
const context = this._contextIdToContext.get(executionContextId)!; const context = this._contextIdToContext.get(executionContextId)!;
const handle = context.createHandle(element).asElement()!; const handle = context.createHandle(element).asElement()!;
this._page._onFileChooserOpened(handle); await this._page._onFileChooserOpened(handle);
} }
async _onWorkerCreated(event: Protocol.Page.workerCreatedPayload) { async _onWorkerCreated(event: Protocol.Page.workerCreatedPayload) {
@ -267,7 +267,7 @@ export class FFPage implements PageDelegate {
// Note: we receive worker exceptions directly from the page. // Note: we receive worker exceptions directly from the page.
} }
async _onWorkerDestroyed(event: Protocol.Page.workerDestroyedPayload) { _onWorkerDestroyed(event: Protocol.Page.workerDestroyedPayload) {
const workerId = event.workerId; const workerId = event.workerId;
const worker = this._workers.get(workerId); const worker = this._workers.get(workerId);
if (!worker) if (!worker)

View File

@ -160,11 +160,11 @@ export class JSHandle<T = any> extends SdkObject {
return null; return null;
} }
async dispose() { dispose() {
if (this._disposed) if (this._disposed)
return; return;
this._disposed = true; this._disposed = true;
await this._context._delegate.releaseHandle(this); this._context._delegate.releaseHandle(this).catch(e => {});
} }
toString(): string { toString(): string {

View File

@ -106,7 +106,7 @@ export class ProgressController {
return result; return result;
} catch (e) { } catch (e) {
this._state = 'aborted'; this._state = 'aborted';
await Promise.all(this._cleanups.splice(0).map(cleanup => runCleanup(cleanup))); await Promise.all(this._cleanups.splice(0).map(runCleanup));
throw e; throw e;
} finally { } finally {
clearTimeout(timer); clearTimeout(timer);

View File

@ -209,7 +209,7 @@ class ContextTracer {
async dispose() { async dispose() {
this._disposed = true; this._disposed = true;
helper.removeEventListeners(this._eventListeners); helper.removeEventListeners(this._eventListeners);
this._snapshotter.dispose(); await this._snapshotter.dispose();
const event: trace.ContextDestroyedTraceEvent = { const event: trace.ContextDestroyedTraceEvent = {
timestamp: monotonicTime(), timestamp: monotonicTime(),
type: 'context-destroyed', type: 'context-destroyed',
@ -219,7 +219,6 @@ class ContextTracer {
// Ensure all writes are finished. // Ensure all writes are finished.
await this._appendEventChain; await this._appendEventChain;
await this._snapshotter.dispose();
} }
private _appendTraceEvent(event: any) { private _appendTraceEvent(event: any) {

View File

@ -143,7 +143,7 @@ export class WKExecutionContext implements js.ExecutionContextDelegate {
async releaseHandle(handle: js.JSHandle): Promise<void> { async releaseHandle(handle: js.JSHandle): Promise<void> {
if (!handle._objectId) if (!handle._objectId)
return; return;
await this._session.send('Runtime.releaseObject', {objectId: handle._objectId}).catch(error => {}); await this._session.send('Runtime.releaseObject', {objectId: handle._objectId});
} }
} }

View File

@ -113,7 +113,7 @@ export class WKPage implements PageDelegate {
promises.push(this.updateHttpCredentials()); promises.push(this.updateHttpCredentials());
if (this._browserContext._permissions.size) { if (this._browserContext._permissions.size) {
for (const [key, value] of this._browserContext._permissions) for (const [key, value] of this._browserContext._permissions)
this._grantPermissions(key, value); promises.push(this._grantPermissions(key, value));
} }
if (this._browserContext._options.recordVideo) { if (this._browserContext._options.recordVideo) {
const size = this._browserContext._options.recordVideo.size || this._browserContext._options.viewport || { width: 1280, height: 720 }; const size = this._browserContext._options.recordVideo.size || this._browserContext._options.viewport || { width: 1280, height: 720 };