Skip to content

Instantly share code, notes, and snippets.

@tiendq
Created March 2, 2020 03:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tiendq/d8374487d7c77c74c788f7f90decd91b to your computer and use it in GitHub Desktop.
Save tiendq/d8374487d7c77c74c788f7f90decd91b to your computer and use it in GitHub Desktop.
// Testing EventEmitter and Promise, async/await
const EventEmitter = require('events');
const http = require('http');
const fs = require('fs').promises;
const myEmitter = new EventEmitter();
async function handler3() {
console.log('handler3: myevent was fired! test Promise');
console.log('reading emitter.js with then');
fs.readFile('./emitter.js', { encoding: 'utf8' }).then(content => console.log(`then: read ${content.length} from emitter.js`));
console.log('reading emitter.js with await');
let content = await fs.readFile('./emitter.js', { encoding: 'utf8' });
console.log(`await: read ${content.length} from emitter.js`);
console.log('handler3 ended');
}
async function main() {
myEmitter.on('myevent', () => console.log('handler1: myevent was fired!'));
myEmitter.on('myevent', () => {
console.log('handler2: myevent was fired! test callback function');
http.get('http://nodejs.org/dist/index.json', (res) => {
const { statusCode } = res;
const contentType = res.headers['content-type'];
let error;
if (statusCode !== 200) {
error = new Error('Request Failed.\n' +
`Status Code: ${statusCode}`);
} else if (!/^application\/json/.test(contentType)) {
error = new Error('Invalid content-type.\n' +
`Expected application/json but received ${contentType}`);
}
if (error) {
console.error(error.message);
// Consume response data to free up memory
res.resume();
return;
}
res.setEncoding('utf8');
let rawData = '';
res.on('data', (chunk) => { rawData += chunk; });
res.on('end', () => {
console.log('GET callback completed');
try {
const parsedData = JSON.parse(rawData);
console.log(parsedData[0].version);
} catch (e) {
console.error(e.message);
}
});
}).on('error', (e) => {
console.error(`Got error: ${e.message}`);
});
});
// 1. await is not waited, comment out 2. to easily see test result
myEmitter.on('myevent', handler3);
console.log('emitting event');
myEmitter.emit('myevent');
console.log('emitted event');
// 2. await is waited, comment out 1. to easily see test result
/*console.log('before handler3');
await handler3();
console.log('after handler3');*/
console.log('>>> I am the last log line');
}
(async function () {
await main();
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment