node.js await仅在异步功能中有效

时间:2020-06-01 07:41:39

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

我有这样的代码

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

1 个答案:

答案 0 :(得分:1)

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

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

相关问题