Medium
Consider the following 2 functionsgetMovie
andrun
:
const Qajax = require('qajax');// Library based on Q, allowing to make promises in HTTP
// Returns an HTTP promise on the url as parameter
function getMovie(url) {
return Qajax.getJSON(url);
}
// Start the generator as a parameter and get a promise
function run(generator) {
var iterator = generator();
function go(result) {
result.value.then(function(value) {
go(iterator.next(value))
});
}
go(iterator.next());
}
What will happen when the following code is called:
run(function*() {
let mov1 = yield getMovie('https://api.myjson.com/bins/3hn4g');//{id:1, title:'Back to the future'}
let mov2 = yield getMovie('https://api.myjson.com/bins/1gro0');//{id:2, title:'Matrix'}
let mov3 = yield getMovie('https://api.myjson.com/bins/53igg');//{id:3, title:'Star Wars'}
console.log(mov1.id, mov1.title);
console.log(mov2.id, mov2.title);
console.log(mov3.id, mov3.title);
});
Author: Jean-marie CléryStatus: PublishedQuestion passed 761 times
Edit
Similar QuestionsMore questions about NodeJS
8
How to define a global variable with Node.js?4
Parse a query string into an object in NodeJS3
Which of these 4 solutions for serving a very large file will be the most optimized in terms of _server resources_ and _loading speed for the client_?3
A simple SocketIO chat server, coupled with Express.2
How to get the result of 3 asynchronous functions in NodeJS