How to correctly use a callback function in NodeJS - node.js

Alright. Trying to make a very simple request here. First code with asynchronous Nodejs. According to everywhere I've checked, I'm doing this right. None of them explained really how callbacks work, they just say what to do, so I have no way of figuring it out intuitively.
const request = require("request");
function fetchData(url, json, callback) {
request({
url: url,
json: json,
method: "get"
}, callback(error, response, body))
}
console.log(fetchData("https://www.yahoo.com", false, function(error, response, body) {
if(!error && response.statusCode == 200) {
return body;
} else {
return error;
}
}));
Thanks

Two things- first, pass the callback variable into request(), don't call the function.
callback vs callback()
Second, you can't use the return value from the callback function. Call console.log() from inside the callback function.
Code with changes:
const request = require("request");
function fetchData(url, json, callback) {
request({
url: url,
json: json,
method: "get"
}, callback)
}
fetchData("http://www.yahoo.com", false, function(error, response, body) {
if(!error && response.statusCode == 200) {
console.log(body);
} else {
console.log(error);
}
}));

Related

How to call rest api in express js

I am new in nodejs and I am using express js, I am calling REST API and want to show the response, but my problem is that the response is showing in console.log but I want to pass the body(response) in assistant.ask, where I am wrong here is my code:
var request = require('request');
let rawInput = function (assistant) {
let rawInput = assistant.getRawInput();
request.post(
'http://xxxxxxx.ngrok.io/api/v1/240/respond',
{ json: { query: rawInput } },
function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
assistant.ask(body);
}
else{
console.log(error);
}
}
);

Why I cannot get the data from body in request method

I try to get the JSON data from a GET request and I can see the information from body in request. How can I get the data?
Currently use NodeJs, basic in JavaScript.
var definedURL="https://api.etherscan.io/api?module=account&action=tokentx&contractaddress=0x6a750d255416483bec1a31ca7050c6dac4263b57&page=1&offset=100&sort=asc&apikey=YourApiKeyToken";
var request = require('request')
var information=[];
request({
url: definedURL,
json: true
}, function (error, response, body) {
if (!error && response.statusCode === 200) {
//console.log(body.result[0]);
information.push(body.result[0]);
}
});
console.log(information);
I expect after this I will see the contain of result coming out, but now it still shows [].
Because you are making asynchronous request. Asynchronous action will get completed after the main thread execution.
console.log(information) // execute before your call
You need to wait for the request call to get completed and received data get pushed to information
There can be two ways to do this -
Async/Await- MDN Reference
var definedURL="https://api.etherscan.io/api?module=account&action=tokentx&contractaddress=0x6a750d255416483bec1a31ca7050c6dac4263b57&page=1&offset=100&sort=asc&apikey=YourApiKeyToken";
var request = require('request')
var information=[];
async () => {
await request({
url: definedURL,
json: true
}, function (error, response, body) {
if (!error && response.statusCode === 200) {
//console.log(body.result[0]);
information.push(body.result[0]);
}
});
console.log(information)
}();
Promise MDN reference
var definedURL="https://api.etherscan.io/api?module=account&action=tokentx&contractaddress=0x6a750d255416483bec1a31ca7050c6dac4263b57&page=1&offset=100&sort=asc&apikey=YourApiKeyToken";
var request = require('request')
var information=[];
var Promise = new Promise((resolve,reject) => {
request({
url: definedURL,
json: true
}, function (error, response, body) {
if (!error && response.statusCode === 200) {
//console.log(body.result[0]);
information.push(body.result[0]);
resolve()
}
});
})
Promise.then(() => {
console.log(information)
})

I am learning about callback functions and API

Here I am learning about Callback functions and API to make weather app on node but when I am running the app on Terminal it says undefined I don't know why?
const request = require("request");
request({
URL: "http://maps.googleapis.com/maps/api/geocode/json?address=1301%20lombard%20street%20philadelphia",
json: true
}, (error, response, body) => {
console.log(body);
});
You are calling request incorrectly. You need to call it like so:
request("http://maps.googleapis.com/maps/api/geocode/json?address=1301%20lombard%20street%20philadelphia", {
json: true
}, (error, response, body) => {
console.log(body);
});
alternatively
request({
url: "http://maps.googleapis.com/maps/api/geocode/json?address=1301%20lombard%20street%20philadelphia",
json: true
}, (error, response, body) => {
console.log(body);
});
Notice the url property in lowercase, whereas yours was uppercase
Refer to https://github.com/request/request#requestoptions-callback

Request within a request in nodejs

I am using request library in nodejs. I need to call new url within the request but I am not able to join the response as it is asynchronouse. How do I send variable a as in below request containing result of request within a request.
request({
url: url,
json: true
}, function (error, response, body) {
var a = [];
a.push(response);
for (i = 0; i < a.length; i++) {
if (a.somecondition === "rightcondition") {
request({
url: url2,
json: true
}, function (error, response, body) {
a.push(response);
});
}
}
res.send(a);
});
Your code seems almost right for what you want. You are just sending the response in the wrong callback. Move it so it only sends after the second request has completed:
request({
url: url,
json: true
}, function (error, response, body) {
var a = [];
a.push(response);
request({
url: url2,
json: true
}, function (error, response, body) {
for(i=0;i<a.length;i++){
if(a.somecondition === "rightcondition"){
a.push(response);
}
}
res.send(a); // this will send after the last request
});
});
You can use async waterfall
'use strict';
let async = require('async');
let request = require('request');
async.waterfall([function(callback) {
request({
url: url,
json: true
}, function(error, response, body) {
callback(error, [response]);
});
}, function(previousResponse, callback) {
request({
url: url2,
json: true
}, function(error, response, body) {
for(i=0;i<previousResponse.length;i++){
if(previousResponse.somecondition === "rightcondition"){
previousResponse.push(response);
}
}
callback(error, previousResponse);
});
}], function(err, results) {
if (err) {
return res.send('Request failed');
}
// the results array will be final previousResponse
console.log(results);
res.send(results);
});

Returning a value from a function in node.js

Still learning node. Based upon the following:
https://github.com/request/request
var request = require('request');
request('http://www.google.com', function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body) // Show the HTML for the Google homepage.
}
})
I wish to create the above as a reusable block of code so thought I'd wrap it in a function passing the URL as a parameter such as:
var request = require('request');
var URL;
var request = require('request');
request('http://www.google.com', function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body) // Show the HTML for the Google homepage.
}
})
function fetchURL (URL) {
request(URL, function (error, response, body) {
if (!error && response.statusCode == 200) {
return body;
}
});
};
var a = fetchURL('http://www.google.com');
console.log(a);
This works however I am unsure of whether "return body" is needed as it also works without this line. Happy to received comments on my coding style too as it's all new to me.
The pattern in Node is to provide a callback as an argument to an asynchronous function. By convention, this callback function has error as its first argument. For example:
function fetchURL(url, callback) {
request(url, function(error, response, body) {
if (!error && response.statusCode == 200) {
callback(null, body);
} else {
callback(error);
}
});
};
fetchURL('http://www.google.com', function(err, body) {
console.log(body);
});
Note that in your snippet, return body; is a return from the anonymous callback function passed into fetchURL(). fetchURL() itself returns nothing.

Resources