unexpected identifier when using await/async in nodejs - javascript

I'm getting unexpected identifier when i use async or await in nodejs. I'm on node version 8.5.0. Completely blocked on this. Is there anyway to fix this?
async function methodA(options) {
rp(options)
.then(function (body) {
serviceClusterData = JSON.parse(body);
console.log("Step 2");
console.log("Getting cluster details from zookeeper");
})
.catch(function (err) {
console.log("Get failed!");
});
}
await methodA(options);
console.log("Step 3!");
Tried this after first answer :
var serviceClusterData = "";
console.log("Step 1!");
////////////////////
async function methodA(options) {
await rp(options)
.then(function (body) {
serviceClusterData = JSON.parse(body);
console.log("Step 2");
console.log("Getting cluster details from zookeeper");
})
.catch(function (err) {
console.log("Get failed!");
});
}
methodA(options);
console.log("whoops Step 3!");
Still gets out of order :(
Step 1
Step 3
Step 2

You can't use await outside of an async function.
async function methodA(options) {
await rp(options)
.then(function (body) {
serviceClusterData = JSON.parse(body);
console.log("Step 2");
console.log("Getting cluster details from zookeeper");
})
.catch(function (err) {
console.log("Get failed!");
});
}
methodA(options);
console.log("Step 3!");

'use strict'
function methodA(options) {
return new Promise(resolve => {
setTimeout(() => {
console.log(1)
resolve(true);
}, 2000);
})
}
//Sync Declartion
async function test() {
//Await declaration
await methodA({});
console.log(2);
}
test();
It seems there's is some syntax error in your code. Above code works in 8.5.0
Reference https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

Related

using try-catch for https but don't catch any error

am using HTTPS to fetch data from a website, what I want to do is to catch any error that could happen,
but the thing is that it catches nothing so this is my main code
test = async() => {
console.log("Hellow")
now = new Date();
const https = require("https");
https.get("website",{ agent: proxyy },
(res) => {
var body = "";
res.on("data", function (chunk) {
body += chunk;
});
res.on("end", function () {
var resp = JSON.parse(body);
data_wanted = resp.data
const desiredItem = data_wanted.find((item) =>
item.name.includes("data")
);
console.log(desiredItem)
});
}
);
};
I tried multiple ways for the error catch like this
async function run() {
try {
await test();
} catch (error) {
console.log(error)
}
and also this way
async function f() {
try{
run = await test()
}catch(e){
console.log("Hello world")
}
}
it tried using the try-catch inside the function but also didn't works, my best guess that the try-catch is being executed before the function finish fetching
EDIT 1: so my real intention is to do a while loop which keep trying until there is not error
const https = require('https');
https.get('https://encrypted.google.com/', (res) => {
console.log('statusCode:', res.statusCode);
console.log('headers:', res.headers);
res.on('data', (d) => {
process.stdout.write(d);
});
}).on('error', (e) => {
console.error(e);
});
https://nodejs.org/api/https.html#https_https_get_options_callback

How do I use aysnc/await in this superagent call?

This is a superagent call, I have imported request(i.e is exported from my superagent component class)
How do I use async/await in this for "res.resImpVariable".
request
.post(my api call)
.send(params) // an object of parameters that is to be sent to api
.end((err, res) => {
if(!err) {
let impVariable = res.resImpVariable;
} else {
console.log('error present');
}
});
I reformulated my answer. I think I was misinterpreting before. You could wrap the entire sequence into a Promise-returning function that resolves after the response callback:
function callSuperagent() {
return new Promise((resolve, reject) => {
return request
.post(my api call)
.send(params) // an object of parameters that is to be sent to api
.end((err, res) => {
if(!err) {
console.log('get response', res);
// uncomment this to see the catch block work
// reject('Bonus error.');
resolve(res);
} else {
console.log('error present', err);
reject(err);
}
});
});
}
Then, you can create an async function and await that:
async function doSomething() {
try {
const res = await callSuperagent();
// uncomment this to see the catch block work
// throw 'Artificial error.';
console.log('res', res);
console.log('and our friend:', res.resImpVariable);
} catch (error) {
throw new Error(`Problem doing something: ${error}.`);
}
}
doSomething();
Or if you don't make doSomething, it would be like this:
callSuperagent()
.then((res) => {
console.log('res', res);
console.log('and our friend:', res.resImpVariable);
})
.catch((err) => {
console.log('err', err);
})

how to wait for writeFile or createWriteStream function to complete in node js?

I am stuck in code I tried different way to wait for write file in node.js but it does not wait .
Below is code
app.post('/createEmp',async (req,res) => {
console.log("Inside createEmp()");
var response = await createEmp(req.body);
console.log(response);
});
async function createEmpFile(fileContentObj){
var response = {};
console.log("filePath :"+filePath);
return new Promise(function(resolve,reject){
fs.writeFile(filePath, fileContentStr, function (err) {
if (err){
console.log("err :"+err);
reject(err);
}
else {
console.log('Saved!');
fileSavedFlag = true;
response.result = fileSavedFlag;
console.log(response);
resolve(response)
};
});
}); // end of promise
/*return new Promise(function(resolve,reject) {
const file = fs.createWriteStream(filePath)
file.write(fileContentStr)
file.end();
file.on("finish", () => { fileSavedFlag = true; resolve(response) });
file.on("error", () => { resolve(response) });
}); */
}
On node js console I can see response but when I called using postman I dont get any response it
Your post route should have res.send as follows
app.post('/createEmp',async (req,res) => {
console.log("Inside createEmp()");
var response = await createEmp(req.body);
console.log(response);
res.send(response)
});

How to get async await / promise based response

So I have a code as below. There is a function that calls 2 axios requests to fetch some sample API data.
function fetch_records(){
var api_url1 = "https://api.github.com/users/mojombo"
var api_url2 = "https://api.github.com/users/defunkt"
axios.get(api_url1)
.then(function (response) {
console.log('Data1 received: ',response);
})
.catch(function (error) {
console.log(error);
})
axios.get(api_url2)
.then(function (response) {
console.log('Data2 received: ',response);
})
.catch(function (error) {
console.log(error);
})
}
And then I want to run this function fetch_records() as below
console.log('Script started');
fetch_records();
console.log('Script ended');
So that the output should be
Script started
... api response data ...
Script ended
But because Javascript is asynchronous, it always gives output as below
Script started
Script ended
... api response data ...
I belive async/await or promise is used to achieve the response I want but I am not sure how to use that exactly.
Just use async/await keywords, but remember JS always is JS.
async function fetch_records() { // a async function
var api_url1 = "https://api.github.com/users/mojombo"
var api_url2 = "https://api.github.com/users/defunkt"
// waterfall way
const data1 = await axios.get(api_url1); // await
console.log('Data1 received: ', data1);
const data2 = await axios.get(api_url2); // await
console.log('Data2 received: ', data2);
// parallel way
// const [data1, data2] = await Promise.all([
// axios.get(api_url1),
// axios.get(api_url2)
// ]);
// console.log(data1, data2);
}
(async () => {
try {
console.log('Script started');
await fetch_records(); // await a async function (Thenable object)
console.log('Script ended');
} catch(err) {
console.error(err);
}
})();
change your function to return promises:
function fetch_records() {
var api_url1 = "https://api.github.com/users/mojombo"
var api_url2 = "https://api.github.com/users/defunkt"
const promise1 = axios.get(api_url1)
.then(function (response) {
console.log('Data1 received: ',response);
})
.catch(function (error) {
console.log(error);
})
const promise2 = axios.get(api_url2)
.then(function (response) {
console.log('Data2 received: ',response);
})
.catch(function (error) {
console.log(error);
});
return [promise1, promise2];
}
now use promise.all :
Promise.all(fetch_records()).then(function(response) {
console.log(response[0], response[1]);
});
function fetch_records() {
var api_url1 = "https://api.github.com/users/mojombo"
var api_url2 = "https://api.github.com/users/defunkt"
return [
axios.get(api_url1),
axios.get(api_url2)
]
}
console.log('Script started');
Promise.all(fetch_records()).then(res => {
console.log(res);
console.log('Script ended');
})
Promise.all will wait till all promises are resolved, more about it
function fetch_records() {
var api_url1 = "https://api.github.com/users/mojombo";
return new Promise((resolve, reject) => {
axios
.get(api_url1)
.then(function(response) {
console.log("Data1 received: ", response);
resolve(response);
})
.catch(function(error) {
console.log(error);
reject(error);
});
});
}
Use with Async/Await :
async function getData() {
let data = await fetch_records();
console.log("Fetch Records :: ", data);
}

handel returned object from dropbix-api (nodejs and express)

i am trying to perform a simple action like upload a file to dropbox,
the file is upload succsfully
what i need is the returned answer that conatain file name,size,path etc.
i know that i lost in the async calls,
and i would like to get some help here please:
exports.uploadFile = async function () {
fs.readFile('./text.txt', function (err, contents) {
if (err) {
console.log('Error: ', err);
}
uploadFile(contents);
});
} ;
async function uploadFile(fileCont) {
let dbx = new Dropbox({ accessToken: APP_KEY });
await dbx.filesUpload({ path: '/basic4.txt', contents: fileCont })
.then(function (response) {
console.log( response);
return response;
})
.catch(function (err) {
console.log(err);
});
}
and i wanted to return the result to fron and so i used this part:
DriveService.uploadFile()
.then((success)=>{
return res.status(200).json({success:true,data:success,message:'list of files recived'});
})
.catch((error)=>{
return res.status(400).json({success:false,data:{},message:error.message});
})
the problem is that the success is always empty since i got lost in the async forest.
can somone please advise?
Thanks
Not sure bout solution in async but, You can use callback like this:
exports.uploadFile = async function (cb) {
fs.readFile('./text.txt', function (err, contents) {
if (err) {
console.log('Error: ', err);
}
uploadFile(contents,cb);
});
} ;
async function uploadFile(fileCont,cb) {
let dbx = new Dropbox({ accessToken: APP_KEY });
await dbx.filesUpload({ path: '/basic4.txt', contents: fileCont })
.then(function (response) {
console.log( response);
cb(response);//Pass response in callback
})
.catch(function (err) {
console.log(err);
});
}
DriveService.uploadFile(function(success) {//this callback will be called from async
return res.status(200).json({success:true,data:success,message:'list of files recived')
})
.catch((error)=>{
return res.status(400).json({success:false,data:{},message:error.message});
})

Categories