RetroCode RetroCode - 2 months ago 16
Node.js Question

How can I pass a callback to a generator that I pass to the "vo" library?

I am trying to understand how callbacks work so I created a function and passed a second argument named 'callback', which I call at the end of the function with 'callback(arr)' . However I am getting an error which says : "callback is not a function" ? Can you please tell me what I am doing wrong?

UPDATE

vo is a nodejs library that takes a generator function* () and runs all it's yields . It's basically a way to handle async code with less callbacks (yes I know I used a callback as well but that's pretty much a choice). A more popular library that does exactly the same thing is co. Link to vo: https://github.com/matthewmueller/vo

var Nightmare = require('nightmare');
var vo = require('vo');

function* MyFunction(query, callback) {
arr = [];
for (i = 0; i < 1; i++) {
arr.push(yield Nightmare({
show: true
}).goto(`http://google.com`)
.inject('js', 'jquery-3.1.0.js')
.evaluate(() => {
var title;
title = 1
extend = 2
var img;
img = 3
var par;
par = 4
url = window.location.href;
var par_arr = [5, 5, 5, 5];


return {
title: title,
img: img,
par: par,
par_arr: par_arr,
url: url
}

}).end()
.catch(function(error, nightmare) {

console.error('Search failed:', error);
}))
}

callback(arr);

return arr;
}

vo(MyFunction)('query', (arr) => {
console.log(arr);
});

Answer

This is working in my enviroment;

var vo = require('vo');

function* idMaker(query, params){

  for (var i = 0; i < 5; i++) {
        console.log(query);
  }
 params.callback("callback value");
  return;
}

vo(idMaker)("param value",{callback: (value)=>console.log(value)}  );

Output:

param value
param value
param value
param value
param value
callback value

I have no time right now to read 'vo' docs to tell you why but I saw a exaplme here.