所以,这是代码
let x = await this.storeFileName(fileName);
因此,我已将 storeFileName
函数声明为异步函数,并且我还返回了一个 promise ,直到这里一切都很好。但我收到一条错误消息:
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)
最佳答案
您不能在未声明为 async
的 new 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);
});
});
}
关于javascript - js async/await 在使用此关键字时抛出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47306609/