【发布时间】: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) =>开头的那个。只需在此处添加async (err, files) =>。下一次开始也是一样的,以file =>开头。 -
告诉我这个错误` await axios({ ^^^^^ SyntaxError: await is only valid in async function`
-
你真的,真的不想将普通的异步回调与基于 Promise 的代码混合在一起。切换到
fs.promises.readdir()并使用该函数的promise 版本,然后您可以使用promise 控制所有控制流。
标签: javascript node.js ecmascript-6 async-await