【问题标题】:node.js await is only valid in async functionnode.js await 仅在异步函数中有效
【发布时间】:2020-06-01 07:41:39
【问题描述】:

我有这样的代码

GetRequests(requestStartId,requestEndId);

async function GetRequests(startId,endId){
    let fileAddress = __dirname + '\\attachments';
    for (let i = startId; i <= endId; i++) {
        if (fs.existsSync(fileAddress + '\\' + i)) {
            await upload(i,fileAddress);
     }
    }
}

/**
upload files
**/
    async  function upload(i,fileAddress){
        fs.readdir(fileAddress + '\\' + i, (err, files) => {
            const newID=await  getNewRequestID(i);
            files.forEach(file => {
                ...
                ...
                 ...
                 await  axios({
                    method: 'post',
                    url: `my_url`,
                    data: form,
                    headers: {
                       [my_header_items]
                    }
                }).then(function (response) {
                    // handle success
                     console.log(response);
                }).catch(function (error) {
                    console.log(error);
                });
            });
        });

    }


   async function getNewRequestID(id) {
        let inputData = {
           [my_input_data]
        };
        form.append('input_data', JSON.stringify(inputData));
       return await axios({
            method: 'get',
            url: `my_url,
            data: form,
            headers: {
                [my_header_item]
            }
        }).then(function (response) {
              return response.data.id;
        }).catch(function (error) {
            console.log(error);
        });
    }

当我运行这个脚本时显示这个错误

const newID=await getNewRequestID(i); ^^^^^ SyntaxError: await is only valid in async function

【问题讨论】:

  • 内部 lambda 不是异步的,以(err, files) =&gt; 开头的那个。只需在此处添加async (err, files) =&gt; 。下一次开始也是一样的,以file =&gt;开头。
  • 告诉我这个错误` await axios({ ^^^^^ SyntaxError: await is only valid in async function`
  • 你真的,真的不想将普通的异步回调与基于 Promise 的代码混合在一起。切换到fs.promises.readdir() 并使用该函数的promise 版本,然后您可以使用promise 控制所有控制流。

标签: javascript node.js ecmascript-6 async-await


【解决方案1】:

async放在下一行的回调函数之前...

fs.readdir(fileAddress + '\\' + i, async (err, files) => { ...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-07
    • 2019-09-12
    • 2022-06-18
    • 2020-12-23
    • 2020-08-13
    • 2020-04-15
    • 2019-06-14
    • 1970-01-01
    相关资源
    最近更新 更多