I am trying to use async/await in NodeJS but my script is throwing a syntax error.
I was under the impression that async/await is supported naively since Node 7.6. When I run node -v I get v7.10.0.
Here is the contents of index.js:
async function getValueAsync() {
return new Promise(function(resolve) {
resolve('foo');
});
}
let value = await getValueAsync();
console.log(value);
But when I invoke this script with node index.js I get:
let value = await getValueAsync();
^^^^^^^^^^^^^
SyntaxError: Unexpected identifier
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.runMain (module.js:605:10)
at run (bootstrap_node.js:427:7)
at startup (bootstrap_node.js:151:9)
I am running Linux Mint 18.1.
How can I get my script to compile and run?
await is only valid inside async functions, so you need, for example, an async IIFE to wrap your code with:
void async function() {
let value = await getValueAsync();
console.log(value);
}();
And, since return values from async functions are wrapped by a promise, you can shorten getValueAsync to simply this:
async function getValueAsync() {
return 'foo';
}
Or don't mark it as async and return a promise from it:
function getValueAsync() {
return new Promise(function(resolve) {
resolve('foo');
});
}
Related
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.
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>
})
My app crashes every time it reaches this line:
const {name, price} = req.query;
^
can't seem to locate the exact answer..here is the error log
SyntaxError: Unexpected token {
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:373:25)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Function.Module.runMain (module.js:441:10)
at startup (node.js:140:18)
at node.js:1043:3
context:
app.get('/products/add' , (req, res) => {
const {name, price} = req.query;
const INSERT_PRODUCTS_QUERY = `INSERT INTO products (name, price) VALUES ('${ name }', ${ price })`;
connection.query(INSERT_PRODUCTS_QUERY, (err,results) => {
if(err)
{
return res.send(err);
}
else
{
return res.send('succesfully added product');
}
});
});
According to node.green, the object destructuring with primitives syntax works after Node.JS v6.4.0, and throws the Unexpected Token { on Node.js versions below that.
Also, the object rest/spread properties only works out of the box from Node v8.6.0. It works in v8.2.1 with the --harmony flag, and throws the Unexpected Token ... on Node.js versions below that.
You tried to use destructuring assignment. AFAIK its support by nodejs v.6+ from a box and from 4.2.2 with flag --harmony_destructuring
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
I had been using node-wit v3.3.2
Today, I wanted to update and use the latest version.
But I'm unable to import node-wit. Not sure why.
I simply copied the code given in their documentation.
'use strict'
var MY_TOKEN="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
const {Wit, log} = require('node-wit');
const client = new Wit({
accessToken: MY_TOKEN,
actions: {
send(request, response) {
return new Promise(function(resolve, reject) {
console.log(JSON.stringify(response));
return resolve();
});
},
myAction({sessionId, context, text, entities}) {
console.log(Session ${sessionId} received ${text});
console.log(The current context is ${JSON.stringify(context)});
console.log(Wit extracted ${JSON.stringify(entities)});
return Promise.resolve(context);
}
},
logger: new log.Logger(log.DEBUG) // optional
});
The terminal shows this:
const {Wit, log} = require('node-wit');
^
SyntaxError: Unexpected token {
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:373:25)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Function.Module.runMain (module.js:441:10)
at startup (node.js:139:18)
at node.js:974:3
Could be the node version you are using. You'll need to use the flag --harmony_destructuring when using a lower version.
Taken from: https://github.com/wit-ai/node-wit
# Node.js <= 6.x.x, add the flag --harmony_destructuring
node --harmony_destructuring examples/basic.js <MY_TOKEN>
# Node.js >= v6.x.x
node examples/basic.js <MY_TOKEN>