简体   繁体   English

“等待仅在异步功能中有效” discord.js

[英]“await is only valid in async function” discord.js

I'm writing this code and I'm getting a "await is only valid in async function" on the line with an arrow below.我正在编写此代码,并且在下面带有箭头的行中得到“等待仅在异步函数中有效”。 I've done a bit of searching around but I'm not entirely sure what's wrong.我已经做了一些搜索,但我不完全确定出了什么问题。

       if (message.attachments.first()) {
        console.log("cool file.")
        if (verifyFile(message.attachments.first())) {
            console.log("epic file!!")
   --->     await request.get(message.attachments.first().url).then(async (data) => {
                fs.writeFileSync(`${directory}/${message.author.id}_unobfuscated.lua`, data)
                var options = {
                    'method': 'POST',
                    'url': 'https://obfuscator.aztupscripts.xyz/Obfuscate',
                    'headers': {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    },

You need to make your function you are currently asynchronous.您需要使您的 function 当前处于异步状态。 You can do it by using one of these options below.您可以使用以下这些选项之一来完成。 (depending on your function type) (取决于您的 function 类型)

Arrow function: async (parameters) => {}箭头 function: async (parameters) => {}

Normal function: async function(parameters){}正常 function: async function(parameters){}

Hope i could help!希望我能帮上忙!

To use await the statement which uses await needs to be directly in the body of an async function.要使用await ,使用await的语句需要直接在async function 的主体中。

For example:例如:

This works这有效

const getValue = async () => 5

const myFunction = async () => {
   let val = await getValue()
   console.log(val)
}

This doesn't这不

const getValue = async () => 5

const myFunction = () => {
   let val = await getValue()
   console.log(val)
}

In your case:在你的情况下:

let myFunc = async () => {
     ...othercode
    if (message.attachments.first()) {
        console.log("cool file.")
        if (verifyFile(message.attachments.first())) {
            console.log("epic file!!")
   --->     await request.get(message.attachments.first().url).then(async (data) => {
                fs.writeFileSync(`${directory}/${message.author.id}_unobfuscated.lua`, data)
                var options = {
                    'method': 'POST',
                    'url': 'https://obfuscator.aztupscripts.xyz/Obfuscate',
                    'headers': {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    },
    ...othercode
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM