javascript - 如何使代码异步?
问题描述
好的,所以我有一个调用 MySQL 数据库的函数,获取一些信息并用它做一些事情。那它应该比较一下。该函数是异步的,但问题是调用 MySQL 数据库的部分在 For 循环内,当我尝试到await
那里时,它说“await 仅在异步函数中有效”。
async function savePosition(con) {
let IDs = [];
let finished = false;
con.query(`SELECT * FROM Callers;`, (err, callers) => {
if (err) throw err;
if (callers.length < 1) throw 'No callers';
for (let i = 0; i < callers.length; i++) {
let maxCalls = -1;
let maxID = "";
let maxLast = "";
for (let j = 0; j < callers.length; j++) {
const uID = callers[j].id;
let isWritten = false;
for (let a = 0; a < IDs.length; a++) {
if (uID == IDs[a]) isWritten = true;
}
if (isWritten) continue;
con.query(`SELECT * FROM Callers WHERE id = '${uID}';`, (e, curr) => {
if (e) throw e;
if (Number(curr[0].calls) > maxCalls) {
maxID = curr[0].id;
console.log(maxID)
maxCalls = curr[0].calls;
}
})
}
IDs[i] = maxID;
console.log("maxid" + maxID);
con.query(`UPDATE Callers SET position = ${i + 1} WHERE id = '${maxID}';`);
}
})
}
从下面的代码,输出是:
maxid
some id
正如我所说,如果我await
输入该con.query()
行,它会给出错误“等待仅在异步函数中有效”。我怎样才能解决这个问题?我希望它先定义maxID,然后在控制台中写入
完整的错误是:
C:\...\Sentry\cmds\setkills.js:33
await con.query(`SELECT * FROM Callers WHERE id = '${uID}';`, (e, curr) => {
^^^^^
SyntaxError: await is only valid in async function
at createScript (vm.js:80:10)
at Object.runInThisContext (vm.js:139:10)
at Module._compile (module.js:616:28)
at Object.Module._extensions..js (module.js:663:10)
at Module.load (module.js:565:32)
at tryModuleLoad (module.js:505:12)
at Function.Module._load (module.js:497:3)
at Module.require (module.js:596:17)
at require (internal/module.js:11:18)
at jsFiles.forEach (C:\...\Sentry\bot.js:93:20)
在bot.js
第 93 行:
let properties = require(`./cmds/${file}`);
第 92 行:
jsFiles.forEach((file) => {
编辑:包括完整的功能。
解决方案
我使用了promise,然后实现了这一点。
var Promise = require('promise');
....
function savePosition(con) {
let getMaxId = ()=>{
return new Promise((resolve,reject)=>{
let maxID;
let counter=callers.length-1;
for (let i = 0; i < callers.length; i++) {
con.query(`SELECT * FROM Callers WHERE id = '${uID}';`, (e, curr) => {
if (e)
throw e;
if (Number(curr[0].calls) > maxCalls) {
maxID = 'some id';
maxCalls = curr[0].calls;
}
if(counter===0) resolve(maxID);
else couonter--;
})
}
})
}
getMaxId().then((maxID)=>{
IDs[i] = maxID;
console.log("maxid" + maxID);
con.query(`UPDATE Callers SET position = ${i + 1} WHERE id = '${maxID}';`);
})
}
推荐阅读
- java - Spring boot:成功注册后尝试自动登录时出现java.lang.StackOverflowError:null
- python - 将 Twillio 消息历史记录插入数据结构或文本文件
- java - 我们可以在接口内使用 lambda 表达式作为接口内的默认或静态实现吗?
- python - Pandas:如何根据特定列上特定值的条件选择数据框中的行
- elasticsearch - Elasticsearch 发布文件: FORBIDDEN/12/index 只读/允许删除(api)]
- birt - Ol start 在 birt 中不起作用
- css - 高度中的 CSS 按钮,带有 flexbox
- java - 输入已更新到数据库中的错误字段
- flutter - Flutter:如果数据为空,FutureBuilder 不会更新
- google-smart-home - 如何对 types.SHUTTER 进行分组,例如 types.LIGHT