Async/Await is not working with node 4.x. Can i have the alternate?

两盒软妹~` 提交于 2021-02-05 11:53:22

问题


Getting below error when i try to use async/await with NodeJs 4.x. Any issue with the below sample code or should i use alternate ?

async function main () { ^^^^^^^^

SyntaxError: Unexpected token function

Code Samples:

(async function () {

        const intgetIDvalue = await fntest(getID);

     }

 })();

 async function fntest (getID) {
   return await knex
     .select('column1')
     .from('tablename')
     .where('ID',getID)
 }

回答1:


try installing asyncawait. It should work for older node versions. Other alternatives are using a callback or promises.

you'll have to require it

  1. npm install asyncawait

  2. require modules.

    var async = require('asyncawait/async');

    var await = require('asyncawait/await');

  3. perform operations.

    (async function () { const intgetIDvalue = await fntest(getID); })();




回答2:


Node 4.x Does not support async await out of the box. In your cade I believe that the easiest way to add support to it will be though babel-node.

Run npm install babel-cli --save-dev

and add this to your package.json

"scripts": {
    "start": "babel-node --presets env src/index.js"
  },

you may need to change src/index.js by your entry point file.

then install the presets

npm install babel-preset-env --save-dev

then start your project using

npm start

this shall do the trick.

The advantage of this over installing asyncawait is that you don't need to change anything in your code, as asyncawait gives you functions that have a similar behavior to async and await operator but does not really transpile your code.

PS: you can specify you presets in a .babelrc file too, feel free to read more about it here https://babeljs.io/docs/en/config-files#file-relative-configuration




回答3:


try async.js http://caolan.github.io/async/

var async = require("async");  
async.map(['file1','file2','file3'], fs.stat, function(err, results) {
    // results is now an array of stats for each file
});

async.parallel([
    function(callback) { ... },
    function(callback) { ... }
], function(err, results) {
    // optional callback
});


来源:https://stackoverflow.com/questions/52473724/async-await-is-not-working-with-node-4-x-can-i-have-the-alternate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!