How to use p-event - 10 common examples

To help you get started, we’ve selected a few p-event examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github developmentseed / observe / app / services / auth.js View on Github external
responseBody
    )
    throw new Error('Response body did not contain an OAuth request token')
  }

  // 2. Ask the user to authorize us
  await Linking.openURL(
    `${
      Config.OAUTH_AUTHORIZE_URL
    }?oauth_token=${requestToken}&oauth_callback=${encodeURIComponent(
      'observe://osm'
    )}`
  )

  // 3. Receive a callback notifying us that we've been authorized
  const evt = await pEvent(Linking, 'url', {
    rejectionEvents: []
  })

  // yes, this is deprecated since Node 11.0.0; node-url doesn't match the
  // URL constructor properly
  // https://github.com/defunctzombie/node-url/issues/37
  const { oauth_token: authorizedToken } = url.parse(evt.url, true).query // eslint-disable-line node/no-deprecated-api

  // check if the token that was authorized is the request token we provided
  if (authorizedToken !== requestToken) {
    throw new Error('Request token did not match authorized token.')
  }

  // 4. Fetch an access token (using the request token)
  const accessTokenResponse = await fetch(Config.OAUTH_ACCESS_TOKEN_URL, {
    headers: oauth.toHeader(
github teambit / bit / src / specs-runner / specs-runner.ts View on Github external
// Don't use ternary condition since if we put it as undefined
  // It will pass to the fork as "undefined" (string) instad of not passing it at all
  // __ids__: ids ? ids.join() : undefined,
  if (ids) {
    // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX!
    baseEnv.__ids__ = ids.join();
  }
  // Merge process.env from the main process
  const env = Object.assign({}, process.env, baseEnv);
  const workerPath = path.join(__dirname, 'worker.js');
  // if (process.pkg) {
  //   const entryPoint = process.argv[1];
  //   workerPath = path.join(entryPoint, '../../dist/specs-runner/worker.js');
  // }
  const child = execa.node(workerPath, args, { env, nodeOptions: ['--no-warnings'] });
  const result = await pEvent(child, 'message');
  const childResult = await child;
  if (!result) {
    return null;
  }

  const deserializedResults = deserializeResults(result);
  if (!deserializedResults) return null;
  if (childResult.all) {
    deserializedResults.childOutput = childResult.all;
  }
  if (deserializedResults.type === 'error') {
    if (deserializedResults.error instanceof Error) {
      throw deserializedResults.error;
    }
    throw new Error(deserializedResults.error);
  }
github szmarczak / http2-wrapper / test / headers.js View on Github external
test('can\'t change headers after they are sent', wrapper, async (t, server) => {
	const request = makeRequest(server.options);
	request.end();

	await pEvent(request, 'finish');
	t.throws(() => request.setHeader('foo', 'bar'), 'Cannot set headers after they are sent to the client');
	t.throws(() => request.removeHeader('foo'), 'Cannot remove headers after they are sent to the client');

	request.abort();
});
github szmarczak / http2-wrapper / test / agent.js View on Github external
test('appends to freeSessions after the stream has ended', singleRequestWrapper, async (t, server) => {
	server.get('/', () => {});

	const agent = new Agent({maxFreeSessions: 2});

	const firstRequest = await agent.request(server.url);
	const secondRequest = await agent.request(server.url);
	const thirdRequest = await agent.request(server.url);

	firstRequest.close();
	secondRequest.close();

	await Promise.all([
		pEvent(firstRequest, 'close'),
		pEvent(secondRequest, 'close')
	]);

	thirdRequest.close();
	await pEvent(thirdRequest, 'close');

	await setImmediateAsync();
	t.is(agent.freeSessions[''].length, 2);

	agent.destroy();
});
github sindresorhus / execa / test / node.js View on Github external
test('node\'s forked script has a communication channel', async t => {
	const subprocess = execa.node('test/fixtures/send');
	subprocess.send('ping');

	const message = await pEvent(subprocess, 'message');
	t.is(message, 'pong');
});
github szmarczak / http2-wrapper / test / headers.js View on Github external
test('`headers` option', wrapper, async (t, server) => {
	const request = makeRequest({...server.options, headers: {foo: 'bar'}});
	request.end();

	const res = await pEvent(request, 'response');
	const data = JSON.parse(await getStream(res));
	t.is(data.headers.foo, 'bar');
});
github szmarczak / http2-wrapper / test / request.js View on Github external
test('sets proper `:authority` header', wrapper, async (t, server) => {
	server.on('session', session => {
		session.origin('https://example.com');
	});

	server.get('/', (request, response) => {
		response.end(request.headers[':authority']);
	});

	const agent = new Agent();
	await agent.getSession(server.url);
	await setImmediateAsync();

	const request = makeRequest('https://example.com', {agent}).end();
	const response = await pEvent(request, 'response');
	const body = await getStream(response);

	t.is(body, 'example.com');

	agent.destroy();
});
github szmarczak / http2-wrapper / test / agent.js View on Github external
test.serial('`timeout` option - endless response', singleRequestWrapper.lolex, async (t, server, clock) => {
	const timeout = 1000;
	const agent = new Agent({timeout});

	const secondStream = await agent.request(server.url);

	const promise = pEvent(secondStream, 'close');

	clock.tick(timeout);

	await promise;
	t.pass();

	agent.destroy();
});
github szmarczak / http2-wrapper / test / agent.js View on Github external
t.is(Object.values(agent.freeSessions).length, 0);
	t.is(Object.values(agent.busySessions).length, 0);

	const first = (await agent.request(server.url, server.options, {
		':path': '/infinite'
	})).end();

	t.is(Object.values(agent.freeSessions).length, 0);
	t.is(Object.values(agent.busySessions)[0].length, 1);

	const second = (await agent.request(server.url, server.options, {
		':path': '/infinite'
	})).end();

	const closeEvents = [pEvent(first.session, 'close'), pEvent(second.session, 'close')];

	t.is(Object.values(agent.freeSessions).length, 0);
	t.is(Object.values(agent.busySessions)[0].length, 2);

	agent.destroy();

	await Promise.all(closeEvents);

	t.is(Object.values(agent.freeSessions).length, 0);
	t.is(Object.values(agent.busySessions).length, 0);
});
github szmarczak / http2-wrapper / test / agent.js View on Github external
testFn('busy sessions can become suddenly covered by shrinking their current streams count', tripleRequestWrapper, async (t, server) => {
		const agent = new Agent({
			maxFreeSessions: 1
		});

		const sessions = {};

		{
			const serverSessionPromise = pEvent(server, 'session');
			const session = await agent.getSession(server.url);
			const serverSession = await serverSessionPromise;

			serverSession.origin('https://example.com');
			await pEvent(session, 'origin');

			sessions.a = {
				client: session,
				server: serverSession,
				requests: [
					session.request(),
					session.request(),
					session.request()
				]
			};
		}

		{
			const serverSessionPromise = pEvent(server, 'session');
			const session = await agent.getSession(server.url);
			const serverSession = await serverSessionPromise;

p-event

Promisify an event by waiting for it to be emitted

MIT
Latest version published 10 months ago

Package Health Score

77 / 100
Full package analysis

Popular p-event functions