简体   繁体   中英

Javascript Async await

I am trying to use await function on AWS S3 upload. But it is getting an error "Await can only be used inside async function"

exports.uploadFiles = async function(fileToUpload, bucketName) {

let s3bucket = new AWS.S3({
    accessKeyId: AccessId,
    secretAccessKey: SecretKey
})

let error = null
let PublicUrls = []
let counter = 0

fileToUpload.forEach((file) => {

    var params = {
        Bucket: bucketName,
        Key: "Somefilename",
        Body: file.buffer,
        ACL: 'public-read'
    }

    const data = await s3bucket.upload(params).promise()

    const Url = { field: file.fieldname, url: data.Location }
    PublicUrls.push(Url)

})
}

You have to make the function withn forEach async like

fileToUpload.forEach(async (file) => { ...

BTW: This is also what the error is saying you

You are out of scope because of the forEach, use a for loop instead...

exports.uploadFiles = async function(fileToUpload, bucketName) {

let s3bucket = new AWS.S3({
    accessKeyId: AccessId,
    secretAccessKey: SecretKey
})

let error = null
let PublicUrls = []
let counter = 0

for (const file of fileToUpload) {

    var params = {
        Bucket: bucketName,
        Key: "Somefilename",
        Body: file.buffer,
        ACL: 'public-read'
    }

    const data = await s3bucket.upload(params).promise()

    const Url = { field: file.fieldname, url: data.Location }
    PublicUrls.push(Url)

})
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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