@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
index.js
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.15.2 linux/amd64