how to make async/await work properly in node js? - node.js

i am new to node js coding i have two functions in my code one of them,i have made async using async keyword but the issue is it doesn't work the output from second function comes before the first function but i want the output of first function before the second function below given is my code
var request = require("request").defaults({jar: true});
var cookieJar = request.jar();
var options = { method: 'POST',
url: 'http://69.30.210.130:8082/api/session',
headers:
{ 'content-type': 'application/x-www-form-urlencoded' },
form: { email: 'admin', password: 'admin' } };
request(options, async function (error, response, body) {
if (error) throw new Error(error);
let bod=await body;
console.log(bod)
});
var options = { method: 'GET',
url: 'http://69.30.210.130:8082/api/devices',
qs: { id: '1' },
headers:
{ 'postman-token': '021a3566-e1ea-4dd4-4ceb-c81ecd25ddd1',
'cache-control': 'no-cache' } };
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});

request uses callbacks as default, it means when you want to chain multiple request, you have to do in this manner:
// first request
request({...}, function(error, response, body1) {
if (error) return console.error('Error', error.message);
// second request
request({...}, function(error, response, body2) {
if (error) return console.error('Error', error.message);
console.log(body1, body2);
});
});
async/await is meant to simplify working with promises, so you can use request-promise:
const rp = require('request-promise');
(async function() { // await can be called only from within an async func
try {
const body1 = await rp({...}); // first request
const body2 = await rp({...}); // second request
console.log(body1, body2);
} catch (e) {
console.error('Error', e.message);
}
})();
Here, the body2 will be resolved after body1 has been resolved. This means async/await brings a synchronous behavior into the asynchronous processing.
You can use axios which is Promises-base out of the box.
EDIT: async from callbacks removed, axios reference added

Related

I can't save the response of a request request in node.js

I created a login function that receives the mail and the pass, to receive the jwt. I have tried that the function returns the jwt but I have not succeeded.
This is the method that I have developed, it has a post request that sends the mail and pass parameters. in the resp variable I try to save the request response, but when invoking the function it prints :
undefined.
login(mail, pass) {
var options = {
'method': 'POST',
'url': 'https://inventario.demos.adlnetworks.com/api/login',
'headers': {
'Content-Type': 'application/json'
},
body: JSON.stringify({ "email": mail, "password": pass })
};
var resp;
var req = request(options, function(error, response) {
if (error) throw new Error(error);
resp = response.body;
});
return resp;
}
The problem is that "request" is an async function. You can't do this
var resp;
var req = request(options, function(error, response) {
if (error) throw new Error(error);
resp = response.body;
});
return resp;
Because "resp" always be undefined. You would need to do something like this
var resp;
var req = request(options, function(error, response) {
if (error) throw new Error(error);
return response.body;
});
But it wont work for you.
The short and easy solution is change the library to make http request, and use "async" and "await" to use easily async functions.
For example:
const fetch = require('node-fetch');
async function main(){
const data = await login();
console.log(data);
}
async function login(){
const url = "https://jsonplaceholder.typicode.com/posts";
const data = {
title: 'foo22222',
body: 'ba222r',
userId: 1
};
const response = await fetch(url, {
method: 'POST',
body: JSON.stringify(data),
headers: {
"Content-type": "application/json; charset=UTF-8"
}
});
const json = await response.json()
return json;
}
main();
In this case i use "node-fetch" library and consume a backend (in login function) that create a post and return its response.

How can I send the response.body out of request module function?

I started by creating a return statement in the request function (I have linked a picture) and then console.log it outside of the function but that didn't work out.
My server code
var options = {
'method': 'POST',
'url': 'http://localhost:8080/ES_Part1/api/user/getUser',
'headers': {
'Content-Type': 'application/x-www-form-urlencoded'
},
form: {
'username': username,
'password': password
}
};
requestToApi(options, function(error, response) {
if (error) throw new Error(error);
console.log("Send form data to remote api and to return the user from Spring")
console.log(response.body);
return response.body
});
var fromapi = response.body;
res.end();
Example:
I suggest you use a Promise-based approach here rather than the callback-style that you're using for requestToApi. If you're using the request package, there is a Promise-based version available.
Alternative solution would be to create a promise yourself, like such:
var requestToApiAsPromise = (options) => {
return new Promise((resolve, reject) => {
requestToApi(options, (error, response) => {
if (error) {
reject(error)
return
}
resolve(response.body)
})
})
}
Then you can use this method in your middleware:
app.post("/checkUser", (req, res) => {
async function process() {
try {
var username = req.body.username
var password = req.body.password
var options = {...}
var response = await requestToApiAsPromise(options)
// response => response.body
// do whatever
res.end()
} catch (error) {
next(error)
}
}
process()
})
This method uses async/await so that it lets you write your code as if you were doing things synchronously, so it's making it easier to make asynchronous calls and have them "wait" before the next line gets executed.
👨‍🏫 If you want to get respose.body outside the handler, than you can use this code below 👇:
// an example get function
app.get('/users', async(req, res) => {
var options = {
'method': 'POST',
'url': 'http://localhost:8080/ES_Part1/api/user/getUser',
'headers': {
'Content-Type': 'application/x-www-form-urlencoded'
},
form: {
'username': username,
'password': password
}
};
const result = new Promise((resolve, reject) => {
requestToApi(options, function(error, response) {
if (error) return reject(error);
return resolve(JSON.parse(response.body));
});
})
// make sure, to use async in your function
// because we're using await here
var fromapi = await result;
// It's working here
console.log(fromapi);
res.end();
})
That code above 👆, only an example that you can use to read response.body. If you want to handle the error from that code above, you can use like this code below:
try {
// make sure, to use async in your function
// because we're using await here
var fromapi = await result;
// It's working here
console.log(fromapi);
} catch(ex) {
// print error response
console.log(ex.message);
}
I hope it's can help you 🙏.

How to migrate to callback nodejs

I need to transform this code into clean code that uses callbacks, because this code does not allow me to use body information elsewhere.
const endpoints = [];
function getDevicesFromPartnerCloud() {
var options = {
method: 'GET',
url: 'https://database-dcda.restdb.io/rest/endpoints',
headers: {
'cache-control': 'no-cache',
'x-apikey': '*****************************'
}
};
request(options, function (error, response, body) {
var data = JSON.parse(body);
data.forEach(function(data, index) {
let endpoint = createSceneEndpoint(data._id, data.name);
endpoints.push(endpoint);
});
});
return endpoints;
}
I think the cleanest way to do it would be to use a Promise to handle the asynchronous request. One of the most important things to remember is that functions should ideally do only one thing. That way, they are easier to test, reason about, and refactor. I would pull the code that actually makes the request into a separate function and have it return the body, then have your getDevicesFromPartnerCloud call that new function, get the data back, and process it however it wants. Most importantly, this "frees" the data from being stuck in the request callback, because you're wrapping it in a promise, and resolving it when the data is available.
Something like:
const endpoints = [];
function requestDevices() {
return new Promise(function(resolve, reject) {
const options = {
method: 'GET',
url: 'https://database-dcda.restdb.io/rest/endpoints',
headers: {
'cache-control': 'no-cache',
'x-apikey': '*****************************',
},
};
request(options, function(error, response, body) {
if (error) {
reject(error)
}
resolve({ response: response, body: body });
});
});
}
async function getDevicesFromPartnerCloud() {
const devicesResponse = await requestDevices();
const data = JSON.parse(devicesResponse.body);
data.forEach(function(data, index) {
const endpoint = createSceneEndpoint(data._id, data.name);
endpoints.push(endpoint);
});
// Do whatever else you need with devicesResponse.body
return endpoints;
}
If you wanted to go more of an es6 direction, maybe something like
let endpoints;
const requestDevices = () =>
new Promise((resolve, reject) => {
request(
{
method: 'GET',
url: 'https://database-dcda.restdb.io/rest/endpoints',
headers: {
'cache-control': 'no-cache',
'x-apikey': '*****************************',
},
},
(error, response, body) => (error ? reject(error) : resolve(body)),
);
});
const getDevicesFromPartnerCloud = async () => {
try {
const body = await requestDevices();
const data = JSON.parse(body);
endpoints = data.map(({ _id, name }) =>
createSceneEndpoint(_id, name),
);
// Do whatever else you need with devicesResponse.body
// doStuff(body)
return endpoints;
} catch (e) {
console.error(e);
}
};

How can I use the value of the body outside this method?

var request = require('request');
var boardsCall = {
method: 'GET',
url: 'https://api.trello.com/1/organizations/xxxxxxxxxx/boards?filter=open&fields=id,name',
qs: {
key: 'xxxxxxxxxxxxxxxx',
token: 'xxxxxxxxxxxxxxxxxxxxxxxxx'
}
};
function test(url, callback) {
request(url, function(error, response, body) {
if (error) {
return callback(error);
}
callback(null, JSON.parse(body));
})
}
const x = test(boardsCall, function(err, body) {
if (err) {
console.log(err);
}
else {
return body;
}
})
console.log(x);
how can I use the value of the body outside?
to use it in other methods later
I am open to any changes best practices, I read a lot and got a bit confused on the topic of callbacks, promises async await.
In my approach request is wrapped with Promise, test function returns Promise response. Inside the main method test function will be executed synchronously. Once the response value assigned to x do remaining processing logic inside the main() method.
var request = require('request');
var boardsCall = {
method: 'GET',
url: 'https://api.trello.com/1/organizations/xxxxxxxxxx/boards?filter=open&fields=id,name',
qs: {
key: 'xxxxxxxxxxxxxxxx',
token: 'xxxxxxxxxxxxxxxxxxxxxxxxx'
}
};
function test(url) {
//Wrapping request callback with Promise
return new Promise((res, rej)=> {
request(url, function(error, response, body) {
if (error) {
rej(error);
}
res(JSON.parse(body));
})
})
}
async function main() {
try {
const x = await test(boardsCall);
console.log("Result : ", x );
// Remaining logic to process based on x value
} catch(e) {
console.error("Error :", e);
}
}
//Calling main method
main()

Q.all array of request promises, not sure how to get the results

Probably an obvious answer to this but I'm not sure what way to take.
request is a node module: https://github.com/request/request
I fill an array of getHistory requests (with different parameters). p = [p1,p2...].
this.app.all('/api/heatmap', function(req,res) {
// fill p here _.each(blabla, p.push(gethistory(someparams...)
var result = [];
function getHistory(params) {
var options = { ...};
var callback = function(error, response, body) {
if(error) { //wtv
} else {
// what to do with the body here ? return body ? result.push(body) ?
}
}
request(options, callback);
}
Q.all(p).then(function() {
});
}
So the problem here is that I when all of the request to be done , put everything in an array/object then send the whole thing to the client. How to have getHistory returning the fetched value (after the request is done ).
Hope it's clear.
The core problem here is that node.js-style callbacks and promises are not compatible. Promises emphasize on return values, node emphasizes on callbacks.
Therefore you need a sort of adapter that wraps node's callback convention properly, a process called Promisifcation. This can be done manually, but it's tedious at best and error-prone when you are not careful. Luckily, since node's conventions are well-established, it can be automated. Q has a few helpers for that, but Bluebird is quite a bit more convenient in this regard.
So the easy way to do it is to switch to Bluebird as the promise library and to use promisifyAll.
var Promise = require('bluebird');
var request = Promise.promisifyAll(require("request"));
this.app.all('/api/heatmap', function(req, res) {
var requests = blabla.map(function (item) {
return request.getAsync({ /* params */ });
});
Promise.all(requests).then(function (responses) {
res.send( JSON.stringify(responses) ); // whatever
}).catch(function (error) {
res.send( "An error ocurred: " + error ); // handle error
});
}
FWIW, here's another answer that shows how the same would look like when done properly with Q:
// promisified request
function requestAsync(options) {
var result = Q.defer();
request(options, function(error, response, body) {
if (error) {
result.reject(error);
} else {
result.resolve(body);
}
});
return result.promise;
}
// returns promises for heatmapVolumes
function getHistory(params) {
return requestAsync({
method: 'GET',
url: 'https://api.kaiko.com/v1/charts/' +
encodeURIComponent(params.exchange) + '/' +
encodeURIComponent(params.pair) +'/history',
qs: params.qs,
headers: {
"Content-Type": "application/json",
"Accept": "application/json"
}
}).then(function (body) {
return heatmapVolume(body, params.exchange, params.pair);
}).catch(function (error) {
// log detailed error and send less revealing message downstream
console.error('error fetching trades', error);
throw new Error('Something went wrong while fetching trades');
});
}
// usage
this.app.all('/api/heatmap', function(req, res) {
getHistory({
exchange: "foo", pair: "bar", qs: "qux"
}).then(function (heatmap) {
res.send(200, heatmap);
}).catch(function (error) {
res.send(500, error);
});
});
Used Q.deferred and it worked as documented \o/
function getHistory(params) {
var deferred = Q.defer();
var options = {
method: 'GET',
url: 'https://api.kaiko.com/v1/charts/' + params.exchange + '/' + params.pair +'/history',
qs:qs,
headers: {
"Content-Type": "application/json",
"Accept": "application/json"
}
}
var callback = function(error, response, body) {
if(error) {
console.log('error fetching trades', error);
res.send(500, 'Something went wrong while fetching trades');
} else {
var body = heatmapVolume(body, params.exchange, params.pair);
// console.log("result!", body.exchange, body.pair);
result.push(body);
// return body;
deferred.resolve();
}
}
request(options, callback);
return deferred.promise;
}

Resources