简体   繁体   中英

Javascript `await` “SyntaxError: Unexpted identifier” even if I am awaiting inside an `async` function

Javascript await gives the following error when I do await inside an async module

let ImagesArray = await getImages();
                            ^^^^^^^^^
SyntaxError: Unexpected identifier
    at createScript (vm.js:80:10)
    at Object.runInThisContext (vm.js:139:10)
    at Module._compile (module.js:607:28)
    at Object.Module._extensions..js (module.js:654:10)
    at Module.load (module.js:556:32)
    at tryModuleLoad (module.js:499:12)
    at Function.Module._load (module.js:491:3)
    at Module.require (module.js:587:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (C:\Users\junai\Desktop\giantbomb-api-test\index.js:8:17)

Here is my code snippet. What am I doing wrong?

    async function getImages(){
        return new Promise(function(resolve, reject) {
            request.get("URL", function (error, response, body) {
                let images = JSON.parse(body).results.map((image)=>{
                    return image.original_url;
                })
                resolve(images);
        });
      })
    }


    module.exports = async function addGame(req, res){
      let ImagesArray = await getImages();
      ImagesArray.forEach(URL => {
          images.push({
              "data": URL,
              "uploadType" : "url",
              "type": "image/jpeg",
              "name": game.name
          })
      });
      console.log(images);
    }

On the other hand the following code works but the output is different:

var images = [{
    "image": {
        "data": "FIRST IMAGE",
        "uploadType": "url",
        "type": "image/jpeg",
        "name": game.name
    }
}];
(async function main() {
    let ImagesArray = await getImages();
    ImagesArray.forEach(URL => {
        images.push({
            "data": URL,
            "uploadType": "url",
            "type": "image/jpeg",
            "name": game.name
        })
    });
    console.log(images); // [{"image" : {"data": "FIRST IMAGE", "uploadType" : "url", "type": "image/jpeg", "name": game.name } }, {...}, {...} ]
})();
console.log(images); // [{"image" : {"data": "FIRST IMAGE", "uploadType" : "url", "type": "image/jpeg", "name": game.name } }]

The problem with the second snippet is that the main function is executed asynchronously. You print images before its execution is finished.

Since an async function returns a Promise , you can use then like this:

var images = [{
    "image": {
        "data": "FIRST IMAGE",
        "uploadType": "url",
        "type": "image/jpeg",
        "name": game.name
    }
}];

async function main() {
   let ImagesArray = await getImages();
   ImagesArray.forEach(URL => {
       images.push({
           "data": URL,
           "uploadType": "url",
           "type": "image/jpeg",
           "name": game.name
       })
    });
});

main().then(() => console.log(images));

Once the top-level await proposal lands , you will be able to just await main .

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