简体   繁体   中英

Executing an async function in a loop

I'm writing a function, that loops through port numbers until it finds an open one:

async function findPort (port, app, logger) {

    const lookupPort = () => {
        return portOpen = new Promise( (resolve, reject) => {
            app.listen(port, () => {
                logger.log("info", `Server listening on port: ${port}`);
                resolve(true);
            })
            .on('error', (err) => { 
                logger.log("warn", "port closed: " + err.port);
                reject(false);
            });
        });
    }

    let portOpen = false;

    while (portOpen === false){
        portOpen = await lookupPort();
        port++;
    }

When executed, it iterates through one port and then trows an exception:

(node:2869) UnhandledPromiseRejectionWarning: Unhandled promise rejection.

There are 2 issues with the code above:

1) while loop stops its execution because lookupPort function throws an error (promise is rejected on reject(false); line) which is not caught ( UnhandledPromiseRejectionWarning: Unhandled promise rejection. ). To fix this try to wrap the code inside while loop into try/catch construction:

while (portOpen === false){
  try {
    portOpen = await lookupPort();
  }
  catch (error) {
    // handle an error here
  }
  port++;
}

Or if you do not want to handle the promise you reject inside lookupPort just remove reject(false); line.

2) lookupPort function assigns a new Promise() to portOpen variable. So even if error will be handled by try/catch , portOpen === false condition will evaluate to false because portOpen will be equal to a Promise object. If there is no reason to assin portOpen the value of the new Promise you should remove it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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