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

為{幸葍}努か 提交于 2021-02-17 05:28:13

问题


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'
                    },

回答1:


You need to make your function you are currently asynchronous. You can do it by using one of these options below. (depending on your function type)

Arrow function: async (parameters) => {}

Normal function: async function(parameters){}

Hope i could help!




回答2:


To use await the statement which uses await needs to be directly in the body of an 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
}


来源:https://stackoverflow.com/questions/61979028/await-is-only-valid-in-async-function-discord-js

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