0

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?

sienki_jenki
  • 111
  • 1
  • 8
  • I don't know the five library you are using, but since the `on` function has a callback, it probably does not return a promise... You would need to wrap you entire return value in a promise and then `resolve` or `reject` depending on which event gets fired. Otherwise it will just register the event handler and return the value. – somethinghere Oct 14 '19 at 16:31

1 Answers1

4

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);
somethinghere
  • 16,311
  • 2
  • 28
  • 42
  • 1
    `reject` should only be called with an `Error`, so +1 to the second option. If you want this Promise to resolve to `true` or `false` instead, then both the `error` and `ready` handler should call `resolve` instead. – Jacob Oct 14 '19 at 16:39
  • 1
    @jacob that is indeed true, good catch (edited post). I prefer the second solution as well, as any info about the event or error gets passed on nicely and can be acted upon properly. No loss of information there. – somethinghere Oct 14 '19 at 16:41