0

So, here's the code

let x = await this.storeFileName(fileName);

So, I've declared the storeFileName function as async and I'm also returning a promise and everything till here is fine. But I'm getting an error that says :

SyntaxError: Unexpected token this which is pointing to the 'this' followed by the await keyword

Btw I'm using an ES6 class and the this keyword refers to the object of that class.

It works without the await keyword but if I put await it throws an error.

What am I doing wrong? Everything seems correct. Can someone throw some light on me.

UPDATE :

These are the two functions.

   async encodeName(x){
     return new Promise((resolve,reject)=>{
        const cipher = crypto.createCipher('aes192', this.PASSWORD);
        let encrypted = cipher.update(x,'utf8', 'hex');
        encrypted += cipher.final('hex');
        if(encrypted.length>240){
         let x = await this.storeFileName(encrypted);
         resolve(`@Fn ${x}`);
      }
      resolve(encrypted);
     });
   }

   async storeFileName(x){
     return new Promise((resolve,reject)=>{
      let doc = { encName: x };
      filesDb = new db(`${this.mntpnt}/__CORE_rigel.pro/x100.db`);
      filesDb.insert(doc,(err,newdoc)=>{
        err?reject():resolve(newdoc._id);
      });   
     });
   }

Btw, I'm doing this on node.js

UPDATE 2 :

Here is the error message

A JavaScript error occurred in the main process
Uncaught Exception:
/home/teja/Documents/Rigel/components/diskEncryptor.js:32
        let x = await this.storeFileName(encrypted);
                      ^^^^
SyntaxError: Unexpected token this
    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/teja/Documents/Rigel/index.js:4:23)
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Shiva Teja
  • 417
  • 4
  • 16
  • Do you have declared as `async` the function where `let x = await this.storeFileName(fileName);` is? – Maluen Nov 15 '17 at 11:50
  • 2
    _"Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers. See: [How to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve/)."_ – Andreas Nov 15 '17 at 11:50
  • @Maluen It's not required but yea I did. – Shiva Teja Nov 15 '17 at 11:52
  • 3
    @Teja `It's not required but yea I did` It certainly is required, you can't use `await` without marking the function your calling it from as `async`. – Keith Nov 15 '17 at 11:56
  • We need to see more code. What does the implementation of `storeFileName` look like. The `this` keyword in __JavaScript__ is the context of the scope, so where are you using it? Again, we need to see more code in order to help. – David Pine Nov 15 '17 at 11:59
  • @Keith No, what I meant was I also declared the function I'm using the await keyword in as async . I ofcourse declared `storeFileName` as async – Shiva Teja Nov 15 '17 at 12:00
  • @Teja, no not `storeFileName`.. The function your calling it from.. – Keith Nov 15 '17 at 12:01
  • Everyone, I updated the question with the complete functions – Shiva Teja Nov 15 '17 at 12:04
  • A Promise callback is also a function, it's not marked as `async`,,. And in any case why not just use `async` ? `new Promise` is not required and would be pointless. – Keith Nov 15 '17 at 12:05
  • @Teja `async storeFileName(x){ return new Promise` Please note what this code is saying, return a promise that returns a promise. Understand that bit and you should be able to fix your code. – Keith Nov 15 '17 at 12:12

3 Answers3

3

Ok, it seems a little bit tricky explaining what you need to do to make your functions async compatible.

So here I've updated your functions to show what I would do.

Notice the util.promisify, this is now baked into a latest version of Node.

async encodeName(x){
  const cipher = crypto.createCipher('aes192', this.PASSWORD);
  let encrypted = cipher.update(x,'utf8', 'hex');
  encrypted += cipher.final('hex');
  if(encrypted.length>240){
    let x = await this.storeFileName(encrypted);
    return `@Fn ${x}`;
  }
  return encrypted;
}

async storeFileName(x){
  let doc = { encName: x };
  filesDb = new db(`${this.mntpnt}/__CORE_rigel.pro/x100.db`);
  pinsert = util.promisify(filesDb.insert);
  const newdoc = await pinsert(doc);
  return newdoc._id;
}
Keith
  • 22,005
  • 2
  • 27
  • 44
3

You cannot use await in the executor function of the new Promise constructor that is not declared async. And you should not anyway!

Use

async encodeName(x) {
  // no Promise constructor here!
  const cipher = crypto.createCipher('aes192', this.PASSWORD);
  let encrypted = cipher.update(x, 'utf8', 'hex');
  encrypted += cipher.final('hex');
  if (encrypted.length > 240) {
    let x = await this.storeFileName(encrypted);
    return `@Fn ${x}`);
  }
  return encrypted;
}
storeFileName(x) {
  // no unnecessary async here
  return new Promise((resolve, reject) => {
    let doc = { encName: x };
    filesDb = new db(`${this.mntpnt}/__CORE_rigel.pro/x100.db`);
    filesDb.insert(doc, (err, newdoc) => {
      err ? reject(err) : resolve(newdoc._id);
    });
  });
}
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
2

You are creating a new function

return new Promise((resolve,reject)=>{

you should declare that function as async too:

return new Promise(async (resolve,reject)=>{

The new function will be

async function encodeName(x){
 return new Promise(async (resolve,reject)=>{
    const cipher = crypto.createCipher('aes192', this.PASSWORD);
    let encrypted = cipher.update(x,'utf8', 'hex');
    encrypted += cipher.final('hex');
    if(encrypted.length>240){
     let x = await this.storeFileName(encrypted);
     resolve(`@Fn ${x}`);
    }
    resolve(encrypted);
 });
}
Maluen
  • 1,753
  • 11
  • 16
  • That would stop the error, but removing the `Promise` in the first is what's needed. – Keith Nov 15 '17 at 12:08
  • @keith Lol, but seriously It printed the exact same error message. – Shiva Teja Nov 15 '17 at 12:11
  • 2
    @Teja, update your snippet, and show what you initially did. You don't want to be mixing Promise constructor with `async` it's meaningless. – Keith Nov 15 '17 at 12:13
  • 1
    @Pascut It's not. – Bergi Nov 15 '17 at 12:59
  • @Bergi You can solve the problem by removing the `new Promise` antipattern completely (and you should), but the fundamental reason for the `SyntaxError` is not adding async to the created arrow function. – Maluen Nov 15 '17 at 13:59