首页 > 解决方案 > 如何使代码异步?

问题描述

好的,所以我有一个调用 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) => {

编辑:包括完整的功能。

标签: javascriptmysqlnode.js

解决方案


我使用了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}';`);
  })
}

推荐阅读