简体   繁体   English

我不知道如何应用异步/等待概念

[英]I don't know how to apply async/await concept

I have the function below: 我有以下功能:

    let updateDevicesStatus = async () => {
       getAllConnectedClients()
       let teste = getAllDevices()

       try {
          devicesDB = await teste
       } catch (e) {
          console.log('deu erro')
       }
       devicesDB.forEach( (currentDevice) => {
          connectedClients.forEach( (currentClient) => {
             if (arduinoNM.connected[currentClient].clientID == currentDevice.clientID) {
                devicesOnline.push(currentDevice)
             } else {
                devicesOffline.push(currentDevice)
             }
          })
       })
}

getAllDevices() retrieve some data on DB, therefore, it takes more time to execute. getAllDevices()检索数据库上的某些数据,因此执行起来需要更多时间。

Node.JS run all these calls asynchronously, what causes an exception, saying that devicesDB is undefined. Node.JS异步运行所有这些调用,这导致异常,表明devicesDB未定义。

I tried to use async/await to make updateDevicesStatus() wait for getAllDevices() execution, but it's not happening... 我试图使用async / await来使updateDevicesStatus()等待getAllDevices()执行,但这没有发生...

What I'm doing wrong? 我做错了什么?

getAllDevices() is not declared with async. getAllDevices()未使用异步声明。 Should I do it? 我应该做吗?

EDIT: 编辑:

getAllDevicesPromise() function: getAllDevicesPromise()函数:

function getAllDevicesPromise() {
            return new Promise((resolve,reject) => {
                resolve(getAllDevices())
            })
        }

getAllDevices() function: getAllDevices()函数:

function getAllDevices() {
            let rst
            let query = Arduino.where({})
            query.find( (err, results) => {
                if (err) return console.error('[ERR] Erro buscando todos os dispositivos do banco para WEB.')
                rst = results
            })
            return rst
        }

I'm testing these function as below: 我正在测试这些功能,如下所示:

let test = await getAllDevicesPromise()
console.log(test)

But it still returning undefined. 但是它仍然返回未定义。 There's something more that I need to do? 还有什么我需要做的吗?

let teste = getAllDevices() ... devicesDB = await teste

^^ This will not work as you expect because you are calling getAllDevices, assigning the return value to teste, and then waiting for nothing. ^^这将无法按您预期的那样工作,因为您正在调用getAllDevices,将返回值分配给teste,然后什么也没有等待。

It should just be: 应该只是:

let devicesDB = await getAllDevices();

you can either : 您可以:

use async/await which is a Syntactic Sugar For Promises in Javascript , you'll need to promisify the getAllDevices() function to resolve with the result of the query, and then await for it in the async updateDevicesStatus 使用async/await这是Javascript中的Promises语法糖) ,您需要对getAllDevices()函数进行承诺,以使用查询结果进行resolve ,然后在async updateDevicesStatus await

function getAllDevices() {
    return new Promise((resolve, reject) => {
        let rst;
        let query = Arduino.where({});
        query.find((err, results) => {
          if (err) reject('[ERR] Erro buscando todos os dispositivos do banco para WEB.');

          resolve(results);
       });
    });
}

let updateDevicesStatus = async () => {
  getAllConnectedClients();

  let devicesDB = await getAllDevices();

  devicesDB.forEach((currentDevice) => {
    connectedClients.forEach((currentClient) => {
      if (arduinoNM.connected[currentClient].clientID == currentDevice.clientID) {
        devicesOnline.push(currentDevice);
      } else {
        devicesOffline.push(currentDevice);
      }
    });
  });
}

or use a callback : 或使用回调:

function getAllDevices(cb) {
  let rst;
  let query = Arduino.where({});
  query.find((err, results) => {
    if (err) cb('[ERR] Erro buscando todos os dispositivos do banco para WEB.');

    cb(null, results);
  })
}

let updateDevicesStatus = () => {
  getAllConnectedClients()

  getAllDevices((err, devicesDB) => {
    if(err) // do something with the error

    devicesDB.forEach((currentDevice) => {
    connectedClients.forEach((currentClient) => {
      if (arduinoNM.connected[currentClient].clientID == currentDevice.clientID) {
        devicesOnline.push(currentDevice);
      } else {
        devicesOffline.push(currentDevice);
      }
    });
  });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM