Search code examples
javascriptasync-awaites6-promisejohnny-five

How to wait for function to execute and get proper promise response?


I'm creating website using Johnny-five,React and node.js to control my Arduino board but I got stuck on handling async/await function. So, user is sending chosen port (COM1) for example to server, server then creates new instance of board

async function checkPortConnection(port) {
    let board = new five.Board({port: port});
    let success;

    await board.on('error', () => {
        success = false;
    });

    await board.on('ready', () => {
        success = true;
    });

    return success;
}

I've thought that keyword await will stop function execution and wait for board response which takes about 7 seconds, but when I do this:

checkPortConnection(port).then((data)=>{
            console.log(data);
        });

I'm getting 'undefined', (because I'm getting success which is undefined?) And after that server will send response if chosen port is correct or not. But my question is, how to get proper response from checkPortConnection() function?


Solution

  • I think the issue is that you are listening for events, but this in and of itself isn't a Promise. Also, if they would be and you would use await you would never reach the code to register the ready event. The following should fix that issue:

    async function checkPortConnection(port) {
        
        return new Promise((resolve, reject) => {
        
          let board = new five.Board({port: port});
    
          board.on('error', error => resolve( false ));
          board.on('ready', event => resolve( true ));
        
        });
        
    }

    Personally I would also do the following, as the Promise will either use then or catch later, so you might want to ignore the boolean bit altogether:

    board.on('error', reject);
    board.on('ready', resolve);