【问题标题】:js async/await throws error on using this keywordjs async/await 在使用这个关键字时抛出错误
【发布时间】:2017-11-15 22:34:50
【问题描述】:

所以,这里是代码

let x = await this.storeFileName(fileName);

所以,我已将 storeFileName 函数声明为异步,并且我还返回了一个承诺,直到这里一切都很好。但我收到一条错误消息:

SyntaxError: Unexpected token this 指向 'this' 后跟 await 关键字

顺便说一句,我使用的是 ES6 类,而 this 关键字指的是该类的对象。

它可以在没有 await 关键字的情况下工作,但如果我输入 await 它会引发错误。

我做错了什么?一切似乎都是正确的。谁能给我一些启发。

更新:

这是两个函数。

   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);
      });   
     });
   }

顺便说一句,我在 node.js 上这样做

更新 2:

这是错误信息

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)

【问题讨论】:

  • 你是否将let x = await this.storeFileName(fileName);所在的函数声明为async
  • “寻求调试帮助的问题(“为什么这段代码不起作用?”)必须包括所需的行为、特定的问题或错误以及在问题中重现它所需的最短代码本身。没有明确问题陈述的问题对其他读者没有用处。请参阅:How to create a Minimal, Complete, and Verifiable example。"
  • @Maluen 这不是必需的,但我做到了。
  • @Teja It's not required but yea I did 当然是必需的,如果不将调用它的函数标记为async,则不能使用await
  • 我们需要查看更多代码。 storeFileName 的实现是什么样的。 JavaScript 中的this 关键字是作用域的上下文,那么你在哪里使用它呢?同样,我们需要查看更多代码才能提供帮助。

标签: javascript node.js async-await ecmascript-2017


【解决方案1】:

您不能在未声明asyncnew Promise 构造函数的执行器函数中使用await。还有you should not

使用

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);
    });
  });
}

【讨论】:

    【解决方案2】:

    好吧,解释你需要做什么来使你的函数async兼容似乎有点棘手。

    所以我在这里更新了你的函数来展示我会做什么。

    注意util.promisify,它现在已被嵌入到最新版本的 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;
    }
    

    【讨论】:

      【解决方案3】:

      你正在创建一个新函数

      return new Promise((resolve,reject)=&gt;{

      您也应该将该函数声明为异步:

      return new Promise(async (resolve,reject)=&gt;{

      新功能将是

      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);
       });
      }
      

      【讨论】:

      • 这将停止错误,但删除第一个 Promise 是需要的。
      • @keith Lol,但说真的,它打印了完全相同的错误消息。
      • @Teja,更新你的 sn-p,并展示你最初做了什么。您不想将 Promise 构造函数与 async 混合使用,这是没有意义的。
      • @Pascut 不是。
      • @Bergi 你可以通过完全删除new Promise 反模式来解决问题(你应该这样做),但SyntaxError 的根本原因是没有向创建的箭头函数添加异步。跨度>
      【解决方案4】:

      首先非常感谢 KeithBergiMaulen 帮助我。我拿起你的代码 sn-ps 并对其进行了测试,我终于理解了它背后的概念。我真的不知道选谁的答案是正确的,你所有的答案似乎都是正确的。无论如何,谢谢你们,这就是我想出的。

         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);
           });
         }
      
         storeFileName(x,mntpnt){
          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);
           });   
          });
        } 
      

      【讨论】:

        猜你喜欢
        • 2021-09-19
        • 1970-01-01
        • 1970-01-01
        • 2016-02-07
        • 2020-10-17
        • 2022-12-09
        • 1970-01-01
        • 2015-05-04
        • 1970-01-01
        相关资源
        最近更新 更多