Revising JS Async/Promises

I have been finding some issues using async functions as well as promises. The following code doesn’t seem to wait for the “await” statement to complete before executing the next line.
I also tried using plain async functions and awaits (without Promise); same result

Should I be using generators?

To understand my question more, please scroll down to read the OUTPUT

 _connection(address) {
        const api = xapi.connect(`ssh://${address}`, {
            username: this.auth.user,
            password: this.auth.password
        }).on('error', (err) => {
                console.log(`\n\rconnection failed for endpoint <${address}>`);
            }).on('ready', api => {
                console.info("this.apis.push(api);")
            });
        return api;
    }
    _getEndpoints() {
        return new Promise( resolve => {
            if (this.endpoints) {
                if (!Array.isArray(this.endpoints)) {
                    this.endpoints = [this.endpoints];
                }
                this.endpoints = this.endpoints.filter( el => CONSTANTS.ip_qualifier.test(el));
                resolve(this.endpoints);                
            }
            else {
                const eps = new Endpoints(CONSTANTS.ENDPOINTS);
                eps.getEndpoints().then( endpoints => resolve(endpoints));
            }
        });
    }
    _firstTask(cb) {
        return new Promise( resolve => {
            let _api = null;
            this._getEndpoints().then( async endpoints => {
                console.info("\r\nendpoints found:\n\r", endpoints);
                for (let ep of endpoints) {
                    _api = await this._connection(ep)
                    if (ep !== '' && ep !== undefined && typeof cb === 'function') {
                        await this._sleep(FOREACH_SLEEP);
                        cb({ api: _api, endpoint: ep, timeout: this.timeout });
                    }
                }
                resolve()
            });
        });
    }
    
    _taskToRun(args) {
        this._firstTask(args[0])
            .then( () => {
                console.log("this.manager.connectionsComplete();");
                this.manager.connectionsComplete();
            })
    }

OUTPUT:
this.manager.connectionsComplete(); // I was expecting this to be executed at the end
connections_complete
this.apis.push(api);
this.apis.push(api);

the issue here was the following:
_connection()

.on('ready', api => {
                console.info("this.apis.push(api);")
            });

the event is triggered later (after ‘ready’ is emitted), so I will need to pass a callback inside .on(‘ready’) listener

1 Like