M
M
Mazino2019-03-04 20:53:43
JavaScript
Mazino, 2019-03-04 20:53:43

How to fetch result from object's async function using async/await?

var sessions = [];
async function setSessionsList() {
  return new Promise((resolve,reject) => {
    connection.query('select `device_ip` from `setup_devices` where `is_enabled` = 1;', (err, data) => {
      if(err) reject(err);
      data.forEach(item => 
        sessions.push(new snmp.createSession(item.device_ip,community,options)));
      return resolve(sessions);
    });
  });
}

How to do the same with async/await without having to append:
setSessionsList().then( resolve => { /*Do somth... */} ).catch( reject => console.error( reject ));

such a code?
Ideally it should be like this:
function foo() {
    let data = setSessionsList();
    console.log(data);//Query result... 
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Somewhere Intech, 2019-03-04
@Mazino

The function is described correctly, it became necessary to add await and make sure that it is in the async scope

async function foo(){
   let sessionsList = await setSessionsList(); //логичнее правда назвать getSessionsList
   console.log(sessionsList); // дождется результата и только потом сработает.
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question