let co = require('co');
const sleep = ms => new Promise(res => setTimeout(res, ms));
co(function*() {
console.log('Welcome to My Console,');
yield sleep(3000);
console.log('Blah blah blah blah extra-blah');
});
This code above is the side effect of the solving Javascript's asynchronous callback hell problem. This is also the reason I think that makes Javascript a useful language in the backend. Actually this is the most exciting improvement introduced to modern Javascript in my opinion. To fully understand how it works, how generator works needs to be fully understood. The function
keyword followed by a *
is called a generator function in modern Javascript. The npm package co
provided a runner function to run a generator.
Essentially generator function provided a way to pause the execution of a function with yield
keyword, at the same time, yield
in a generator function made it possible to exchange information between inside the generator and the caller. This provided a mechanism for the caller to extract data from a promise
from an asynchronous call and to pass the resolved data back to the generator. Effectively, it makes an asynchronous call synchronous.