SyntaxError: missing ) after argument list, When using async - javascript

Why am I getting this error When I use async?
My Code:
bot.onText(/\/start/, async msg => {
const opts = {
parse_mode: 'Markdown' ,
reply_markup: JSON.stringify({
keyboard: StartKeyboard,
resize_keyboard: true,
one_time_keyboard: true
})
};
await bot.sendMessage(msg.chat.id, 'Hi', opts);
});
Error:
bot.onText(/\/start/, async msg => {
^^^^^
SyntaxError: missing ) after argument list
I'm using node.js v6.11.0 with "dependencies":
{ "babel-polyfill": "^6.23.0",
"cheerio": "^1.0.0-rc.2",
"dotenv": "^4.0.0",
"firebase": "^4.1.2",
"firebase-admin": "^5.0.0",
"node-telegram-bot-api": "^0.27.1",
"request": "^2.81.0" },

Your version of NodeJS (6.11 LTS) is too old and does not support the async/await features. The syntax error is a result of the Javascript interpreter not recognizing the async token and getting confused about arguments.
Upgrade to NodeJS 7.6 or later. https://www.infoq.com/news/2017/02/node-76-async-await
In prior versions, the only way to perform asynchronous behaviour is to use promises.

If you don't want to/can't update your node version, try using babel presets.
I had the same error using ES6 with jest (node v6.9.1).
Just add these two modules to your dependencies
npm install --save babel-preset-es2015 babel-preset-stage-0
And add a file .babelrc to your root dir with the following code:
{ "presets": ["es2015", "stage-0"] }
And if you are not using it already, install babel-cli and run your application with babel-node command
sudo npm install -g babel-cli
babel-node app.js

If you're seeing this error with a newer version of Node, it's probably a syntax or some other error before the line Node is pointing out.
For instance, consider the snippet below.
router.get("/", function (req, res, next) {
try {
res.json(await mySvc.myFunc());
} catch (err) {
console.error(err.message);
next(err);
}
});
With node -v reporting v14.17.6, this gives:
myapp $ DEBUG=myapp:* npm start
> myapp#0.0.0 start /home/me/myapp
> node ./bin/www
/home/me/myapp/routes/myroute.js:7
res.json(await mySvc.myFunc());
^^^^^
SyntaxError: missing ) after argument list
The error, of course, is on the first line of the snippet. Adding an async on that line, thus,
router.get("/", async function (req, res, next) {
fixes the issue.

Related

Error: knex: Required configuration option 'client' is missing

I'm new to Node.js, please help me.
What is wrong?
Using typescript, SQLite3 and Knex, with migration.
I get the error when running "yarn knex: migrate" or "knex migrate: latest":
$ knex migrate:latest
Requiring external module ts-node/register
Error: knex: Required configuration option 'client' is missing
These are my files:
package.json:
{
"name": "backend",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"scripts": {
"start": "ts-node-dev --transpile-only --ignore-watch node-modules --respawn
src/server.ts",
"knex:migrate": "knex --knexfile knexfile.ts migrate:latest",
"knex:migrate:rollback": "knex --knexfile knexfile.ts migrate:rollback"
},
"devDependencies": {
"#types/express": "^4.17.11",
"ts-node": "^9.1.1",
"ts-node-dev": "^1.1.6",
"typescript": "^4.2.4"
},
"dependencies": {
"espress": "^0.0.0",
"express": "^4.17.1",
"knex": "^0.95.4",
"sqlite3": "^5.0.2"
}
}
knexfile.ts:
import path from'path';
module.exports = {
cliente: 'sqlite3',
connection: {
filename: path.resolve(__dirname, 'src', 'database', 'resp.sqlite')
},
migrations: {
directory: path.resolve(__dirname, 'src', 'database', 'migrations'),
},
useNullAsDefault: true,
};
Migration 00_create_organizacoes.ts:
import knex from 'knex';
export async function up(knex: knex) {
return knex.schema.createTable('organizacoes', table => {
table.increments('id').primary();
table.string('razaosocial_org').notNullable();
table.integer('atividade_org').notNullable();
table.timestamp('criacao_org').defaultTo(knex.fn.now());
table.timestamp('atualizacao_org').defaultTo(knex.fn.now());
});
}
export async function down(knex: knex) {
return knex.schema.droptable('organizacoes');
};
My file structure:
enter image description here
Unsuccessful in other treatments.
Looks like you have a typo in your knexfile.ts
The name of the missing property is client and not cliente
The Requiring external module ts-node/register message you get is not the issue, the issue is that in the knexfile.ts the client property is not read. From the example above change the cliente property to client and it is fixed.
What if you have no spelling error, client exist in your configuration, and you are getting this message? Are you using a env file? If yes, In your knexfile.ts print the value from your env file. If it returns undefined, it means that no value was read for the env file. Check if you have the dotenv package installed and configured properly. Also check that your env file has a key called client and the value is available and in the knexfile.ts ensure you are calling the right key from your env.
Finally if the problem is not solved and every other thing is in-place, require dotenv in your package.json file before running a command as shown below.
"migrate:latest": "ts-node -r dotenv/config ./node_modules/knex/bin/cli.js migrate:latest
The ts-node -r dotenv/config ensures that the details in the env file are added to the environment.
The ./node_modules/knex/bin/cli.js starts the knex cli so that the remaining part which is a knex command can be executed.

How to use ES6(esm) imports/exports in cloud functions

import functions from 'firebase-functions';
import UtilModuler from '#utilModuler'
exports.helloWorld = functions.https.onRequest((request, response) => {
response.send("Hello from Firebase!");
});
import UtilModuler from '#utilModuler';
^^^^^^^^^
SyntaxError: Unexpected identifier
at Module._compile (internal/modules/cjs/loader.js:721:23)
Caveats
I'm using third party libraries(#utilModuler) which were written via import/exports. Possible workarounds:
Fork library and generate cjs file with rollup.
esm works like a charm but it cause unnesecary memory consumptions
Question: is there are a way how to use hybrid import cjs and esm in google cloud function?(except options which I described above)
Would be nice to use in deploy function something like --experimental-modules
It looks like, ESM support has been added by the latest version of the firebase CLI (https://github.com/firebase/firebase-tools/releases/tag/v9.15.0):
$ npm install -g firebase-tools # Get the latest firebase-cli
$ firebase deploy --only functions # Deploy as usual
and
You must select nodejs14 runtime.
You must manually include latest version of #google-cloud/functions-framework dependency.
e.g.
// package.json
...
"engines": {
"node": "14"
},
"type": "module",
"dependencies": {
"#google-cloud/functions-framework": "^1.9.0",
...
},
and an example function:
// index.js
import functions from "firebase-functions";
export const helloWorld = functions.https.onRequest((request, response) => {
response.send("Hello from Firebase!");
});
"devDependencies": {
"#babel/core": "^7.2.0",
"#babel/preset-env": "^7.2.0",
"#babel/register": "^7.0.0"
}
.babelrc
{
"presets": ["#babel/preset-env"]
}
entry point node.js app
require("#babel/register")({})
// Import the rest of our application.
module.exports = require('./index.js')

TypeError: createTestCafe is not a function

I am getting this error when I copied runner code from TestCafe site and try to run it. I have testcafe 1.6.0 on Ubuntu 18.04
Below is my runner,
const createTestCafe = require('/usr/local/bin/testcafe');
let testcafe = null;
createTestCafe('localhost', 1337, 1338)
.then(tc => {
testcafe = tc;
const runner = testcafe.createRunner();
return runner
//.src(['__test__/*.js', 'tests/func/fixture3.js'])
//.browsers(['chrome:headless --no-sandbox --disable-gpu', 'safari'])
.src(['./__tests__/testcafe1.js'])
.browsers(['chrome'])
.run();
})
.then(failedCount => {
console.log('Tests failed: ' + failedCount);
testcafe.close();
});
Below is my package.json
{
"private": true,
"scripts": {
"test": "testcafe 'chrome:headless --no-sandbox' ./__tests__/*.js --hostname localhost"
},
"devDependencies": {
"chalk": "^2.4.2",
"prettier": "^1.18.2",
"testcafe": "*",
"rimraf": "^2.6.3"
}
}
Below is the error:
ERROR Cannot prepare tests due to an error.
TypeError: createTestCafe is not a function
at Object.createTestCafe (/app/code/testcafe_runner.js:6:1)
at Function._execAsModule (/usr/local/lib/node_modules/testcafe/src/compiler/test-file/api-based.js:50:13)
at ESNextTestFileCompiler._runCompiledCode (/usr/local/lib/node_modules/testcafe/src/compiler/test-file/api-based.js:150:42)
at ESNextTestFileCompiler.execute (/usr/local/lib/node_modules/testcafe/src/compiler/test-file/api-based.js:174:21)
at ESNextTestFileCompiler.compile (/usr/local/lib/node_modules/testcafe/src/compiler/test-file/api-based.js:180:21)
at Compiler._getTests (/usr/local/lib/node_modules/testcafe/src/compiler/index.js:86:31)
at Compiler._compileTestFiles (/usr/local/lib/node_modules/testcafe/src/compiler/index.js:98:35)
at Compiler.getTests (/usr/local/lib/node_modules/testcafe/src/compiler/index.js:111:34)
at Bootstrapper._getTests (/usr/local/lib/node_modules/testcafe/src/runner/bootstrapper.js:81:26)
at Bootstrapper._bootstrapParallel (/usr/local/lib/node_modules/testcafe/src/runner/bootstrapper.js:214:39)
I'm following the code from Testcafe https://devexpress.github.io/testcafe/documentation/using-testcafe/programming-interface/runner.html
What am I doing wrong here?
You try to require TestCafe's executable file instead of the TestCafe's library. Likely it is located in /usr/lib/node_modules/testcafe or in /usr/local/lib/node_modules/testcafe. You can use the following command to find the path to your globally installed modules:
npm ls -g
However, it's really better to install TestCafe locally if you want to use it as a library. If you plan to run and distribute your test runner script as a standalone CLI tool, you can achieve it with creating a NPM package and adding your runner script to the bin section in package.json: https://docs.npmjs.com/files/package.json#bin
You forgot the keyword function
function createTestCafe(...)

SyntaxError: Unexpected token function - Async Await Nodejs

I was experimenting on using Node version 6.2.1 with some of my code. Had plans to migrate most of the hyper-callback oriented codes to something that looks cleaner and maybe performs better.
I have no clue why, the terminal throws up an error when I try to execute the node code.
helloz.js
(async function testingAsyncAwait() {
await console.log("Print me!");
})();
Logs-
BOZZMOB-M-T0HZ:rest bozzmob$ node helloz.js
/Users/bozzmob/Documents/work/nextgennms/rest/helloz.js:1
(function (exports, require, module, __filename, __dirname) { (async function testingAsyncAwait() {
^^^^^^^^
SyntaxError: Unexpected token function
at Object.exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:513:28)
at Object.Module._extensions..js (module.js:550:10)
at Module.load (module.js:458:32)
at tryModuleLoad (module.js:417:12)
at Function.Module._load (module.js:409:3)
at Function.Module.runMain (module.js:575:10)
at startup (node.js:160:18)
at node.js:456:3
BOZZMOB-M-T0HZ:rest bozzmob$ node -v
v6.2.1
What am I missing? Please throw me some light on the same.
Update 1:
I tried to use Babel as Quentin suggested, But, I am getting the following error still.
Updated Code-
require("babel-core/register");
require("babel-polyfill");
(async function testingAsyncAwait() {
await console.log("Print me!");
})();
Logs-
BOZZMOB-M-T0HZ:rest bozzmob$ babel helloz.js > helloz.trans.js
SyntaxError: helloz.js: Unexpected token (3:7)
1 | require("babel-polyfill");
2 |
> 3 | (async function testingAsyncAwait() {
| ^
4 | await console.log("Print me!");
5 | })();
Async functions are not supported by Node versions older than version 7.6.
You'll need to transpile your code (e.g. using Babel) to a version of JS that Node understands if you are using an older version.
That said, versions of Node.js which don’t support async functions are now all past End Of Life and are unsupported, so if you are using an earlier version you should very strongly consider upgrading.
Nodejs supports async/await from version 7.6.
Release post: https://v8project.blogspot.com.br/2016/10/v8-release-55.html
Node.JS does not fully support ES6 currently, so you can either use asyncawait module or transpile it using Babel.
install
npm install --save asyncawait
helloz.js
var async = require('asyncawait/async');
var await = require('asyncawait/await');
(async (function testingAsyncAwait() {
await (console.log("Print me!"));
}))();
If you are just experimenting you can use babel-node command line tool to try out the new JavaScript features
Install babel-cli into your project
$ npm install --save-dev babel-cli
Install the presets
$ npm install --save-dev babel-preset-es2015 babel-preset-es2017
Setup your babel presets
Create .babelrc in the project root folder with the following contents:
{ "presets": ["es2015","es2017"] }
Run your script with babel-node
$ babel-node helloz.js
This is only for development and testing but that seems to be what you are doing. In the end you'll want to set up webpack (or something similar) to transpile all your code for production
babel-node sample code : https://github.com/stujo/javascript-async-await/tree/15abac
If you want to run the code somewhere else, webpack can help and here is the simplest configuration I could work out:
Full webpack example : https://github.com/stujo/javascript-async-await
node v6.6.0
If you just use in development. You can do this:
npm i babel-cli babel-plugin-transform-async-to-generator babel-polyfill --save-dev
the package.json would be like this:
"devDependencies": {
"babel-cli": "^6.18.0",
"babel-plugin-transform-async-to-generator": "^6.16.0",
"babel-polyfill": "^6.20.0"
}
create .babelrc file and write this:
{
"plugins": ["transform-async-to-generator"]
}
and then, run your async/await script like this:
./node_modules/.bin/babel-node script.js
Though I'm coming in late, what worked for me was to install transform-async-generator and transform-runtime plugin like so:
npm i babel-plugin-transform-async-to-generator babel-plugin-transform-runtime --save-dev
the package.json would be like this:
"devDependencies": {
"babel-plugin-transform-async-to-generator": "6.24.1",
"babel-plugin-transform-runtime": "6.23.0"
}
create .babelrc file and write this:
{
"plugins": ["transform-async-to-generator",
["transform-runtime", {
"polyfill": false,
"regenerator": true
}]
]
}
and then happy coding with async/await
include and specify the node engine version to the latest, say at this time I did add version 8.
{
"name": "functions",
"dependencies": {
"firebase-admin": "~7.3.0",
"firebase-functions": "^2.2.1",
},
"engines": {
"node": "8"
},
"private": true
}
in the following file
package.json

babel 6 async / await: Unexpected token

Im having trouble getting async / await transforms working.
What am I missing?
My .babelrc:
{
"presets": [ "es2015", "stage-0" ]
}
My package.json (snipped):
{
"babel-core": "^6.1.2",
"babel-plugin-transform-runtime": "^6.1.2",
"babel-preset-es2015": "^6.1.2",
"babel-preset-stage-0": "^6.1.2"
}
Output:
babel src/server
SyntaxError: src/server/index.js: Unexpected token (7:21)
5 |
6 | try {
> 7 | let server = await server('localhost', env.NODE_PORT || 3000)
| ^
8 | console.log(`Server started on ${server.info.uri}`)
9 | } catch (err) {
10 | console.error('Error starting server: ', err)
According to this post you need to have babel-polyfill
Babel 6 regeneratorRuntime is not defined with async/await
Hopefully it'll help you :)
EDIT:
It doesn't have to be babel-polyfill but it's the only one I used.
As Gothdo said: the await keyword has to be in a function scope. Moreover, this function definition has to have the async keyword.
This means that you can not have the await keyword on the top-level scope.
Looks like async/await is only available in babel-preset-stage-3
http://babeljs.io/docs/plugins/preset-stage-3/
You can compile them yourself using the transform-async-to-module-method plugin, this allows you to compile them down to bluebird co-routines which requires ES6 generators (available in node4).
Or if you need to compile it back to ES5 so it's compatible for browsers you can use transform-async-to-generator and facebook's regenerator.
I've written about how to set up your babel config here http://madole.xyz/async-await-es7/
Use the Async to generator transform.
Installation
$ npm install babel-plugin-transform-async-to-generator
Usage
Add the following line to your .babelrc file:
{
"plugins": ["transform-async-to-generator"]
}
It's recommended to upgrade to Babel 7 and use babel-env as opposed to stages (see here: https://github.com/babel/babel-upgrade).
There's a command you can use to upgrade accordingly:
npx babel-upgrade

Categories