SyntaxError: Unexpected token function in async function? - node.js

Hi everyone I'm beginner in Nodejs and mongoose.I have tried to insert and retrieve the data in mongoose.I'm using async await function to execute one by one (sequence).can anyone help me? Thanks in advance....
i.e: I want to execute (Async await)concept (SEQUENCE STEP)
1.connect the db
2.create the user
3.find the user.
I'm getting the error :
async function calltaskone(){
^^^^^^^^
SyntaxError: Unexpected token function
at Object.exports.runInThisContext (vm.js:78:16)
at Module._compile (module.js:543:28)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3)
at Module.runMain (module.js:605:10)
at run (bootstrap_node.js:420:7)
at startup (bootstrap_node.js:139:9)
at bootstrap_node.js:535:3
Code for your reference:
'use strict';
const mongoose=require('mongoose');
const calldbconnect=()=>{
return new Promise((resolve,reject)=>{
if(true){
mongoose.connect('mongodb://vdsd:vdwdwh12dw3,#ds11dwdw.mlab.com:1w5664/vorganisation',{useNewUrlParser:true},(err,db)=>{
if(err){
console.log(err);
reject('Db is not connected');
}
else{
resolve('Db is connected');
}
});
}
});
}
const schemadesign=new mongoose.Schema({
clientName:String,
clientId:Number,
clientAddress:String
});
const modeldata=mongoose.model('clientInfo',schemadesign);
const data=[{
clientName:'VIGNESH Mack',
clientId:4128,
clientAddress:'UK'
},{
clientName:'VIGNESH Tokyo',
clientId:4988,
clientAddress:'USA'
}];
function calldatasave(){
return new Promise((resolve,reject)=>{
modeldata.create(data,(err,a,b)=>{
if(err){
reject(`Error occured while data saved ${err}`);
}
else{
resolve('Data saved successfully');
}
});
});
}
const calldatafind=()=>{
return new Promise((resolve,reject)=>{
if(true){
console.log('try to find');
modeldata.find({'clientId':4988},(err,data)=>{
if(err){
reject(`Error occured while find data: ${err}`)
}
else{
console.log(data);
resolve('Data found');
}
});
}
});
}
async function calltaskone(){
const a=await calldbconnect();
console.log(a);
const b=await calldatasave();
console.log(b);
const c=await calldatafind();
console.log(c);
}
calltaskone();

I believe you're using a older version of Node. Async functions are not supported by Node versions older than version 7.6. You can check here.
If you want to use async/await then you need to transpile using Babel for your node version.
Edit:
As you said you are using v7.3, you can use (from v7.0 to v7.5) the --harmony flag to enable the experimental features. To know more about the flag, check this out: What does `node --harmony` do?

Related

cant send a message to a specific channel

I have a simple dc bot, code goes like this. I tried to simplfy it to make it more readable
const client = new Discord.Client();
...
client.on('ready', () => {
client.channels.cache.get('315445287374028800').send("works here");
});
setInterval(( () =>{
try{
removeHTML(downloadHTML);
} catch(err){
console.log(err);
}
}),30000);
...
...
let removeHTML = function(callback){
client.channels.cache.get('315445287374028800').send("WORKS HERE");
readHTML();
...
}
let readHTML = function(){
console.log("dolar is read");
//client.channels.cache.get('315445287374028800').send("DOESNT WORK HERE");
fs.readFile(dir + '/index.html' , 'utf-8', function(err,html){
if(err)
console.log(err);
else{
//client.channels.cache.get('315445287374028800').send("DOESNT WORK HERE");
if(isPeak){
//client.channels.cache.get('315445287374028800').send("DOESNT WORK HERE");
}
}
});
}
seems like send function doesnt work in callback functions but how can i fix this?
Error type: same error for all ("DOESNT WORK HERE") lines :
TypeError: Cannot read property 'send' of undefined
at readHTML (C:\Users\user\Desktop\Discord Bot\index.js:142:18)
at Object.<anonymous> (C:\Users\user\Desktop\Discord Bot\index.js:182:1)
at Module._compile (internal/modules/cjs/loader.js:1015:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1035:10)
at Module.load (internal/modules/cjs/loader.js:879:32)
at Function.Module._load (internal/modules/cjs/loader.js:724:14)
at Function.executeUserEntryPoint [as runMain]
I have turned all functions to async-await instead and it worked

Express : using await before bcrypt.compare gives error

I am trying to use bcrypt to compare user's password with stored password.
But Express is giving error is I use await before bcrypt.compare
Here is the code :
app.post ('/users/login', (req, res) => {
const user = users.find(user=> user.name === req.body.user)
if (user == null) {
return res.status(400).send('Can Not find user');
} else {
try{
if ( await bcrypt.compare(req.body.password, user.password)) {
res.send("Success");
} else {
res.send("Incorrect PAssword");
}
} catch {
return res.status(500).send('Some Error has occurred');
}
}
});
I am getting this error :
C:\Data\Ashish\projects\jwtAuthentication\app.js:32
if ( await bcrypt.compare(req.body.password, user.password)) {
^^^^^^
SyntaxError: Unexpected identifier
at Module._compile (internal/modules/cjs/loader.js:723:23)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)
[nodemon] app crashed - waiting for file changes before starting...
Please help to find the mistake..
Regards,
Ashish
You forgot to add async to the callback function.
app.post ('/users/login', (req, res) => {
Should be:
app.post ('/users/login', async (req, res) => {
Await will work only with async functions.
It is different from the chrome console. In the console you can directly use await keyword, but in case of node.js, you need to specify async nature of the parent function in which you want to use await.
For further reference, you can refer to this link.

node.js then() not working

I am new to node.js so I am trying to understand promises and wait on node.js. I want to print the file note.txt.
Here is my code
var fs = require('fs');
fs.readFile('note.txt','utf8').then(contents => console.log(contents))
.catch(err => console.error(err));
When I run above code. I get the following error.
fs.readFile('note.txt','utf8').then(contents => console.log(contents))
TypeError: Cannot read property 'then' of undefined
at Object.<anonymous> (/Applications/nodeApps/test/index.js:13:31)
at Module._compile (module.js:635:30)
at Object.Module._extensions..js (module.js:646:10)
at Module.load (module.js:554:32)
at tryModuleLoad (module.js:497:12)
at Function.Module._load (module.js:489:3)
at Function.Module.runMain (module.js:676:10)
at startup (bootstrap_node.js:187:16)
at bootstrap_node.js:608:3
And I try another method for the same thing.
var fs = require('fs');
async function read_file(){
var file_data = await fs.readFile('note.txt','utf8');
return file_data;
}
console.log(read_file());
And I get following error
Promise { <pending> }
(node:6532) [DEP0013] DeprecationWarning: Calling an asynchronous function without callback is deprecated.
I get the same error when I run with --harmony. I m not sure if there is bug on my code or what is wrong. Please help me understand.
My Environment
Node version: v8.9.0
node -p process.versions.v8: 6.1.534.46
You're getting errors because fs.readfile doesn't return a promise; hence then doesn't exist. For you to use the function as a promise, you will need to wrap it up as a promise; you could use something like bluebird or Q.
Thank you for the answers. I learned that function must return promise in order to use then() and catch(). So the code should be like this
var fs = require('fs');
function read_file(){
return new Promise(function(resolve, reject) {
fs.readFile('note.txt','utf8',function(err,file){
if(err){
return reject(err);
}else{
resolve(file);
}
});
});
}
read_file().then(
(data)=>{
console.log('success: '+data);
}
).catch((err)=>{
console.log('error: ',err);
});
If you use NodeJs v10, try fs.promises:
var fs = require('fs').promises; // v10.0 use require('fs/promises')
fs.readFile('note.txt','utf8').then(contents => console.log(contents))
.catch(err => console.error(err));
If not, use readFileSync:
// This code can use for node v10 or lowwer
var fs = require('fs');
var data = fs.readFileSync('a.json');
console.log(data);
try to use the async await
function (async err => {
if (err) {
console.err ....}
await .... <other function included or comes after then .>
await ... <other function included>
})

How to read data from console in Node.js?

Actually I have tried one code. This code is working fine but I want to access this information outside of callback function. But i am unable to find solution.
var prompt = require('prompt');
prompt.start();
prompt.get(['username', 'email'], function (err, result) {
console.log('Command-line input received:');
console.log(' username: ' + result.username);
console.log(' email: ' + result.email);
data = result.username;
});
console.log(data);
Here if i'm trying to retrieve print data variable it show's error.
Admins-MacBook-Pro:Basic node programs Sandeep$ node Node3.js
prompt: username: /Users/Sandeep/Desktop/NodeJS/Node example/Basic node programs/Node3.js:22
console.log(data);
^
ReferenceError: data is not defined
at Object.<anonymous> (/Users/Sandeep/Desktop/NodeJS/Node example/Basic node programs/Node3.js:22:13)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.runMain (module.js:604:10)
at run (bootstrap_node.js:394:7)
at startup (bootstrap_node.js:149:9)
at bootstrap_node.js:509:3
You could use promise, check docs about promise and newer es 6 Async/ await. With promise you could use something like this:
var prompt = require('prompt');
function getPromt () { return new Promise( (resolve, recect) => {
prompt.start();
prompt.get(['username', 'email'], function (err, result) {
console.log('Command-line input received:');
console.log(' username: ' + result.username);
console.log(' email: ' + result.email);
resolve( result.username);
});
});
}
getPromt().then(data =>
console.log('After promise ' + data), ()=>{});
"You won't be able to access that variable outside the callback function. The reason is, the Node.js has a special feature of passing a callback function as the next block of code to be executed after performing an asynchronous IO task."
Refer to this one: how can find return variable value outside anonymous function in node js mysql query function
You can also check this link to learn how to handle with async flow: http://book.mixu.net/node/ch7.html

Calling function depending on updated fields

I want to call different functions depending on the updated model fields.
My code looks like:
update(req, res){
return LED
.findById(req.params.LEDId)
.then(LED => {
if (!LED) {
return res.status(400).send({
message: 'LED Not Found',
});
}
return LED
.update(req.body, {fields: Object.keys(req.body)})
.then(() => res.status(200).send(LED))
.catch((error) => res.status(400).send(error));
})
.catch((error) => res.status(400).send(error));
},
So my plan was to integrate some if-clauses to get the changed value and call some functions depending on the changes.
If-Clauses:
if(req.body.status || LED.status){
BLE.changeStatus(req.body.device_ID,req.body.status);
}else if(req.body.prog || LED.prog){
BLE.changeProg(req.body.device_ID,req.body.prog);
}else if(req.body.white || LED.white){
BLE.changeWhite(req.body.device_ID,req.body.white);
}else if(req.body.color || LED.color){
BLE.changeColor(req.body.device_ID,req.body.color);
}else if(req.body.brightness || LED.brightness){
BLE.changeBrightness(req.body.device_ID,req.body.brightness);
}
Where do I need to integrate these if-clauses that the functions can be called?
I've tried to integrate it in a .then() before I send the field updates to DB but I get the following error while trying to start the server:
SyntaxError: Unexpected token if
at createScript (vm.js:53:10)
at Object.runInThisContext (vm.js:95:10)
at Module._compile (module.js:543:28)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3)
at Module.require (module.js:498:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (/home/pi/projekt/server/controllers/index.js:1:75)
[nodemon] app crashed - waiting for file changes before starting...
EDIT
I'm a bit further now..
I've wrote the update function like:
update(req, res){
return LED
.findById(req.params.LEDId)
.then(LED => {
if (!LED) {
return res.status(404).send({
message: 'LED Not Found',
});
}
if(req.body.status){
changeStatus(req.params.LEDId,req.body.status);
console.log('STATUS CHANGED');
} if(req.body.prog){
changeProg(req.params.LEDId,req.body.prog);
console.log('PROG CHANGED');
} if(req.body.white){
changeWhite(req.params.LEDId,req.body.white);
console.log('WHITE CHANGED');
} if(req.body.color){
changeColor(req.params.LEDId,req.body.color);
console.log('COLOR CHANGED');
} if(req.body.brightness){
console.log('BEFORE BRIGHNTESS CHANGED')
changeBrightness(req.params.LEDId,req.body.brightness)
console.log('BRIGHNTESS CHANGED')
}
return LED
.update(req.body, {fields: Object.keys(req.body)})
.then(() => res.status(200).send(LED))
.catch((error) => res.status(400).send(error));
})
.catch((error) => res.status(400).send(error));
},
I've tested it and it jumps to the changeBrightness function. There I want to work with noble. Code looks like this:
changeBrightness(LEDId,updateBrightness){
console.log('BEGINN CHANGEBRIGHTNESS FUNCTION')
var uuid = "4711";
var brightness = updateBrightness;
console.log('BRIGHTNESS', brightness)
console.log('UUID', uuid)
console.log('AFTER CHANGEBRIGHTNESS VAR')
// Connect to client, find Service, find Characteristic and write status
noble.connect(uuid, function(error){
noble.discoverServices([lightningServiceUuid], function(error, service){
var tempLightningService = service[0];
writeFile("SUCCESS -- Discovered Service on UUID");
tempLightningService.discoverCharacteristics([brightnessCharacteristic], function(error, characteristics){
var tempBrightnessCharacteristic = characteristics[0];
writeFile("SUCCESS -- Discovered Characterisitc on UUID");
console.log('IN THE MIDDLE OF CHANGEBRIGHTNESS FUNCTION')
tempBrightnessCharacteristic.write(new Buffer(brightness), true, function(error){
writeFile("SUCCESS -- Wrote brightness characteristic");
});
});
});
});
//Disconnect from client
noble.disconnect(function(error){
writeFile("SUCCESS -- Disconnected from Client");
});
console.log('END CHANGEBRIGHTNESS FUNCTION')
}
I'm currently working with a fake uuid for testing purposes.. So my output looks like this when I start the server and execute a update request:
[nodemon] restarting due to changes...
[nodemon] starting `node ./bin/www`
Executing (default): SELECT "id", "device_id", "name", "group", "status", "device_type", "prog", "white", "color", "brightness", "createdAt", "updatedAt" FROM "LEDs" AS "LED" WHERE "LED"."id" = '1';
BEFORE BRIGHNTESS CHANGED
BEGINN CHANGEBRIGHTNESS FUNCTION
BRIGHTNESS 5
UUID 4711
AFTER CHANGEBRIGHTNESS VAR
PUT /api/led/1 400 357.728 ms - 2
Why does it stop before the noble function? What do I need to change?

Resources