Я не знаю, как применить концепцию async / await - PullRequest
0 голосов
/ 30 июня 2018

У меня есть функция ниже:

    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() извлечение некоторых данных из БД, поэтому выполнение занимает больше времени.

Node.JS выполняет все эти вызовы асинхронно, что вызывает исключение, говоря, что devicesDB не определена.

Я пытался использовать async / await, чтобы updateDevicesStatus() ожидал getAllDevices() выполнения, но этого не происходит ...

Что я делаю не так?

getAllDevices() не объявлено с асинхронным. Должен ли я сделать это?

EDIT:

Функция getAllDevicesPromise ():

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

Функция 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
        }

Я тестирую эти функции, как показано ниже:

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

Но он все еще возвращается неопределенным. Есть что-то еще, что мне нужно сделать?

Ответы [ 2 ]

0 голосов
/ 30 июня 2018

вы можете либо:

используйте async/await, который является синтаксическим сахаром для обещаний в Javascript , вам нужно будет обещать функцию getAllDevices() до resolve с результатом запроса, а затем await за это в async updateDevicesStatus

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

или используйте обратный вызов:

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);
      }
    });
  });
}
0 голосов
/ 30 июня 2018

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

^^ Это не будет работать так, как вы ожидаете, потому что вы вызываете getAllDevices, присваиваете возвращаемое значение teste, а затем ничего не ждете.

Это должно быть просто:

let devicesDB = await getAllDevices();

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...