0

I'm trying to get make the async calls bellow (they are async because of a external API, not my design) to run sequentially, now I managed to have foo be awaited by it's calling function but I'm having trouble awaiting for foo2 because I get the following error on the async line

JS ERROR: SyntaxError: missing ) after argument list

What am I missing?

ps: Also is there a better way to "return" a value from the callback than setting a global variable and accessing it from outside?

 foo(nick) {
        return new Promise((resolve, reject) async () => {
            async_foo(par, [],
                (c, res) => {
                    let par2;
                    try {
                        par2 = c.somefun(res);
                    } catch (e) {
                        logError(e, `Some error`);
                        return;
                    }

                    let output = await this.foo2(par2);

                    resolve(output);
                });
        });
    }
 foo2(par2) {
        return new Promise((resolve, reject) => {
            par2.asyncfun(
                null, this.callback.bind(this, par2));
        });
    }

Thank you in advance

ptomato
  • 56,175
  • 13
  • 112
  • 165
  • 1
    Note that `(resolve, reject) async () => { ... }` is invalid syntax, I expect this is where the error is coming from. You probably need to delete the `async ()` here. – ptomato Apr 10 '20 at 03:36

1 Answers1

1

I think you're just trying to do too much in one Promise:

async function(nick) {
    let res1 = await new Promise((resolve, reject) => {
        async_foo(par, [], (c, res) => {
            try {
                resolve(async_foo_finish(res));
            } catch (e) {
                reject(e);
            }
        });
    });

    return new Promise((resolve, reject) => {
        res1.asyncfunc(null, (obj, res) => {
            try {
                resolve(obj.asyncfun_finish(res));
            } catch (e) {
                reject(e);
            }
        });
    });
}

foo('something').then(output => {
    log('output');
}).catch(e => {
    logError(e);
});

It's hard to give good advice, since you're not showing real functions.

One of the main purposes of Promises/async-await is to avoid complicated callback nesting. You should generally break your chain of functions into separate Promises, then await them one after the other.

andy.holmes
  • 3,383
  • 17
  • 28