问题
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