Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
144
rated 0 times [  150] [ 6]  / answers: 1 / hits: 24001  / 9 Years ago, wed, october 14, 2015, 12:00:00

I am trying to retrieve a json object to use it in another module, but I have a problem with callback. I have the error callback is not a function. I use callback because my variable description is undefined, so i guess it's a problem of asynchronous.



Could you help me plz :)



var leboncoin = function () {
var http = require('http')
var bl = require('bl')

http.get(http://www.website.com, function (response, callback) {
response.pipe(bl(function (err, data) {
if (err) {
return console.error(err)
callback(err);
}
var data = data.toString()

var brand = ...
var model = ...
var releaseDate = ...
var km = ...
var fuel = ...
var gearbox = ...

description.Brand = brand;
description.Model = model;
description.Year = releaseDate;
description.KM = km;
description.Fuel = fuel;
description.Gearbox = gearbox;

callback(description);
return (description)

/*console.log(description.Brand);
console.log(description.Model);
console.log(description.Year);
console.log(description.KM);
console.log(description.Fuel);
console.log(description.Gearbox);*/

}))
})
}

exports.leboncoin = leboncoin;





var module = require('./leboncoin');
var res = module.leboncoin();

console.log(res);

More From » node.js

 Answers
14

Callbacks aren't magic that just appear. You need to define a parameter to your function and pass the callback you want to use.



// --------------------------v
var leboncoin = function (callback) {
var http = require('http')
var bl = require('bl')

http.get(http://www.website.com, function (response) {
response.pipe(bl(function (err, data) {
if (err) {
callback(err);
return;
}
var data = data.toString()
var description = { /* your description object */ }

callback(description);
}))
})
}

exports.leboncoin = leboncoin;





var module = require('./leboncoin');

// -----------------vvvvvvvv
module.leboncoin(function(res) {
console.log(res);
});

[#64739] Monday, October 12, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
arthur

Total Points: 729
Total Questions: 107
Total Answers: 109

Location: China
Member since Mon, Aug 22, 2022
2 Years ago
;