如何使代码异步?

gwbalxhn  于 2021-06-23  发布在  Mysql
关注(0)|答案(2)|浏览(344)

好的,我有一个函数,调用mysql数据库,获取一些信息,并用它做一些事情。然后它应该比较一下。这个函数是异步的,但问题是调用mysql数据库的部分在for循环中,当我尝试 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

就像我说的,如果我把 awaitcon.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) => {

编辑:包括全部功能。

bksxznpy

bksxznpy1#

下面是使用承诺和 async/await 要允许您在异步查询中使用更同步的编码样式,请执行以下操作:

const util = require('util');

async function savePosition(con) {
    con.queryPromise = util.promisify(con.query);
    let IDs = [];
    let finished = false;
    let callers = await con.queryPromise(`SELECT * FROM Callers;`);

    if (callers.length < 1) throw new Error('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;

            let curr = await con.queryPromise(`SELECT * FROM Callers WHERE id = '${uID}';`);
            if (Number(curr[0].calls) > maxCalls) {
                maxID = curr[0].id;
                console.log(maxID)
                maxCalls = curr[0].calls;
            }
        }

        IDs[i] = maxID;
        console.log("maxid" + maxID);
        await con.queryPromise(`UPDATE Callers SET position = ${i + 1} WHERE id = '${maxID}';`);
    }
}

你可以这样称呼它:

savePosition(con).then(() => {
    console.log("savePosition() completed successfully");
}).catch(err => {
    console.log("Error in savePosition(), err);
});
cig3rfwq

cig3rfwq2#

我用承诺和承诺来实现这一点。

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}';`);
  })
}

相关问题