@rpichioli/

Coroutine and generators in promises management

Nodejs

A simple working app using Coroutine and Generator to manage promises, responses and data.

fork
loading
Files
  • index.js
  • package-lock.json
  • package.json

This Plugin Crashed!

Error: Error: must not create an existing file {"type":"CREATE_FILE","wid":"0.8523210507472956","path":"index.js","file":{"path":"index.js","content":{"asEncoding":{"base64":"Ly8gSW1wb3J0aW5nIGluc3RhbGxlZCBOUE0gbW9kdWxlcwpjb25zdCBmZXRjaCA9IHJlcXVpcmUoJ25vZGUtZmV0Y2gnKTsKCi8qKgogKiBAZGVzY3JpcHRpb24gR2VuZXJhdG9yCiAqLwpmdW5jdGlvbiAqIGdlbmVyYXRvciAoKSB7Cgljb25zdCBhcGkgPSAnaHR0cHM6Ly9qc29ucGxhY2Vob2xkZXIudHlwaWNvZGUuY29tL2NvbW1lbnRzLzE1JzsKCgkvLyBQcm9taXNlIGhhbmRsaW5nIHRoZSByZXNwb25zZQoJY29uc3QgcmVzcG9uc2UgPSB5aWVsZCBmZXRjaChhcGkpOwoJLy8gUHJvbWlzZSBoYW5kbGluZyBKU09OIGRhdGEKCWNvbnN0IGNvbW1lbnQgPSB5aWVsZCByZXNwb25zZS5qc29uKCk7CgkvLyBEZXN0cnVjdGluZyB0aGUgb2JqZWN0IGludG8gdmFyaWFibGVzCgljb25zdCB7bmFtZSxlbWFpbCxib2R5fSA9IGNvbW1lbnQ7CgoJY29uc29sZS5pbmZvKCdGZXRjaGVkIGNvbW1lbnQ6Jyk7Cgljb25zb2xlLmxvZygnLSBOYW1lOicsIG5hbWUpOwoJY29uc29sZS5sb2coJy0gRW1haWw6JywgZW1haWwpOwoJY29uc29sZS5sb2coJy0gQm9keTonLCBib2R5KTsKfQoKLyoqCiAqIEBkZXNjcmlwdGlvbiBDb3JvdXRpbmUKICovCmxldCBjb3JvdXRpbmUgPSAoZm4pID0+IHsKCS8vIEdlbmVyYXRvciBpbnN0YW5jZQoJY29uc3QgZ2VuZXJhdG9yID0gZm4oKTsKCS8vIFJ1bm5pbmcgdGhlIGZpcnN0IGdlbmVyYXRvciBpdGVyYXRpb24KCWxldCB7dmFsdWUsIGRvbmV9ID0gZ2VuZXJhdG9yLm5leHQoKTsKCgl2YWx1ZS50aGVuKHJlc3BvbnNlID0+IHsKCQkvLyBSdW5uaW5nIHRoZSBuZXh0IGl0ZXJhdGlvbgoJCWxldCB7dmFsdWUsIGRvbmV9ID0gZ2VuZXJhdG9yLm5leHQocmVzcG9uc2UpOwoJCS8vIFJ1bm5pbmcgdGhlIG5leHQgaXRlcmF0aW9uIHNlbmRpbmcgZGF0YQoJCXZhbHVlLnRoZW4oY29tbWVudCA9PiBnZW5lcmF0b3IubmV4dChjb21tZW50KSk7Cgl9KTsKfQoKLy8gR29pbmcgYWhlYWQgd2l0aCBleGVjdXRpb24hCmNvbnN0IGV4ZWN1dGlvbiA9IGNvcm91dGluZShnZW5lcmF0b3IpOwo="},"asBuffer":null},"loaded":true}}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
// Importing installed NPM modules
const fetch = require('node-fetch');

/**
 * @description Generator
 */
function * generator () {
	const api = 'https://jsonplaceholder.typicode.com/comments/15';

	// Promise handling the response
	const response = yield fetch(api);
	// Promise handling JSON data
	const comment = yield response.json();
	// Destructing the object into variables
	const {name,email,body} = comment;

	console.info('Fetched comment:');
	console.log('- Name:', name);
	console.log('- Email:', email);
	console.log('- Body:', body);
}

/**
 * @description Coroutine
 */
let coroutine = (fn) => {
	// Generator instance
	const generator = fn();
	// Running the first generator iteration
	let {value, done} = generator.next();

	value.then(response => {
		// Running the next iteration
		let {value, done} = generator.next(response);
		// Running the next iteration sending data
		value.then(comment => generator.next(comment));
	});
}

// Going ahead with execution!
const execution = coroutine(generator);
node v10.16.0