簡體   English   中英

node.js await 僅在異步中有效 function

[英]node.js await is only valid in async function

我有這樣的代碼

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

在以下行中的回調 function 之前放置async ...

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM