async function
should have await
expression JS-0116async
function without any await
expressions118 return receiver
119 }
120
121 router.post("/api/post", async (req, res) => {122 try {123 let message = validateMessage(req.body.message);124 validatePID(req.body.pid);125 let reply_id = validateReplyID(req.body.reply_id);126 let receiver = validateReceiver(req.body.receiver);127128 let __dirname = server.dirname129 const file_names = ["","","","",""]130 if(isNotNull(req.files)) {131 for(let file_index=0;file_index<5;file_index++) {132 if(isNotNull(req.files[`file_${file_index}`])) {133 let file = req.files[`file_${file_index}`]134 const file_id = server.genstring(20)135 const file_name = `${file_id}/${(file.name.substring(0,25)).replace(/\.[^/.]+$/, "")}`136 let extension = file.name.substring(file.name.lastIndexOf("\.")+1)137 file_names[file_index]=`${file_name}${(extension in image_types && ".webp") || extension}`138 server.ensureExists(`${__dirname}/user_uploads/${file_id}`,undefined,async (err)=>{139 if(err) {140 console.error(err)141 return;142 }143 if(extension in image_types) {144 writeFile(`${__dirname}/user_uploads/${file_name}.webp`,await sharp(file.data).webp({mixed:true,effort:6}).toBuffer(),(err2)=>{145 if(err2)console.error(err2)146 })147 server.ensureExists(`${__dirname}/user_uploads/previews/${file_id}`,undefined,async (error) => {148 if(error) {149 console.error(error)150 return;151 }152 writeFile(`${__dirname}/user_uploads/previews/${file_name}.webp`,await sharp(file.data).resize(100,100,{fit: "inside"}).webp({mixed:true,effort:6}).toBuffer(),(error2)=>{153 if(error2)console.error(error2)154 })155 })156 } else {157 file.mv(`${__dirname}/user_uploads/${file_name}.${extension}`,(err2)=>{158 if(err2)console.error(err2)159 })160 }161 })162 }163 }164 }165166 let sql = `START TRANSACTION;INSERT INTO ipost.posts (post_user_name,post_text,post_time,post_receiver_name,post_from_bot,post_reply_id,file_0,file_1,file_2,file_3,file_4) VALUES (?,?,?,?,?,?,?,?,?,?,?);SELECT LAST_INSERT_ID() as ID;COMMIT;`;167 let values = [encodeURIComponent(res.locals.username), message, Date.now(), receiver, res.locals.isbot, reply_id,...file_names];168 con.query(sql, values, function (err, result) {169 if (err){170 res.status(500)171 res.json({"error":"there's been an interal error"})172 console.error(err)173 return;174 }175 let post_obj = {176 post_user_name: encodeURIComponent(res.locals.username),177 post_text: req.body.message,178 post_time: Date.now(),179 post_special_text: "",180 post_receiver_name: req.body.receiver,181 post_from_bot: res.locals.isbot,182 post_reply_id: reply_id,183 user_avatar: res.locals.avatar,184 files: file_names,185 post_id: result[0].ID186 };187 let message = {188 message: "new_post",189 data: post_obj190 };191 let messagestr = JSON.stringify(message);192 //console.log(5,server.wss.clients); /* DEBUG: Log websocket clients */193 server.wss.clients.forEach(function(ws) {194 //console.log(5,ws); /* DEBUG: Log websocket clients */195 ws.send(messagestr);196 });197 res.json({ "success": "successfully posted message" });198 console.log(5, `posted new message by ${res.locals.username} : ${req.body.message}`);199 });200 } catch (error) {201 if(error.statusCode) {202 res.status(error.statusCode)203 res.json({ "error": error.message, "status": error.statusCode });204 } else {205 console.error("some error: ", error)206 res.status(500)207 res.json({"error":"internal server error", "status": 500})208 }209 }210 /* #swagger.security = [{211 "appTokenAuthHeader": []212 }] */213 });214 return createPID
215};
216export default {
async
function without any await
expressions 11var currentChannel
12
13let socket = new WebSocket(wss_URI);
14socket.addEventListener("message", async function (_event) { 15 console.info("TODO: add websocket support to dms") 16 // return 17 // if(wss_server === event.origin) { 18 // let data = event.data; 19 // let ds = JSON.parse(data) 20 // let message = ds.message 21 // let item = ds.data 22 // let username = decodeURIComponent(item.post_user_name) 23 // if(message === "new_post") { 24 // await createPost(decodeURIComponent(item.post_user_name),decodeURIComponent(item.post_text),item.post_time,item.post_special_text,highest_id+1,item.post_from_bot,item.post_reply_id,true) 25 // if(user["username"]!==username)mainNoti(username) 26 27 // let highest_known_posts = await (await fetch(`/api/getPostsLowerThan?id=${highest_id+28}&channel=${currentChannel}`)).json() 28 // for (let i = 0; i < highest_known_posts.length; i++) { 29 // if(document.getElementById(highest_known_posts[i].post_id) === undefined) { 30 // main() 31 // return; 32 // } 33 // } 34 // highest_id++; 35 // } 36 // } 37}) 38
39var cd = true //inversed "cooldown"
40
A function that does not contain any await
expressions should not be async
(except for some edge cases
in TypeScript which are discussed below).
Asynchronous functions in JavaScript behave differently than other functions in two important ways:
Promise
.await
operator inside them.Functions are made async
so that we can use the await
operator inside them.
Consider this example:
async function fetchData(processDataItem) {
const response = await fetch(DATA_URL);
const data = await response.json();
return data.map(processDataItem);
}
Asynchronous functions that don't use await
might be an unintentional result of refactoring.
Note: This issue ignores async generator functions.
Generators yield
rather than return
a value and async
generators might yield all the values of another async generator without ever actually needing to use await
.
In TypeScript, one might feel the need to make a function async
to comply with type signatures defined by an interface.
Ideally, the code should be refactored to get rid of such restrictions, but sometimes that isn't feasible
(For example, when we are implementing an interface defined in a 3rd party library like Next.js).
This situation can easily be circumvented by returning the value with a call to Promise.resolve
:
interface HasAsyncFunc {
getNum: () => Promise<number>
}
// Not recommended:
const o: HasAsyncFunc = {
async getNum() { return 1 }
}
// Recommended:
const o: HasAsyncFunc = {
// We only use `Promise.resolve` to adhere to the type
// of the surrounding object.
getNum() { return Promise.resolve(1) }
}
It is also advised to add a comment near the redundant promise to make the intent clear.
async function fetchData(): string {
// `readFileSync` is a synchronous function that blocks
// the main thread, and thus does not need to be `await`ed
return fs.readFileSync("data.txt", "utf-8");
}
performAction(async () => { console.log("no awaits in here") });
async function fetchDataAsync(): Promise<string> {
return await fs.readFile("data.txt", "utf-8")
}
performAction(async () => { await writeToFile(data) });
// Allow empty functions.
async function no_op() {}