3

Say I have the following:

const a = new A();
await a.getB().action();

A.prototype.getB() is async as-well as B.prototype.action(). If I try to await on the chaining of the functions I get an error: TypeError: a.getB(...).action is not a function.

If I am separating the chaining of the functions and awaiting each promise it works fine. Is there a way to chain these promises and await them together?

3
  • Have you tried (await a.getB()).action()? Commented Jul 7, 2019 at 12:54
  • 1
    Try: await (await a.getB()).action() or await a.getB().then(result => result.action()) Commented Jul 7, 2019 at 12:54
  • I was hoping there's some syntatic sugar I could get away with, guess I will have to await for each promise Commented Jul 7, 2019 at 13:04

2 Answers 2

4

You need to await hem both:

const a = new A();
const b = await a.getB();
await b.action();

Or

const a = new A();
await a.getB().then(b => b.action());
Sign up to request clarification or add additional context in comments.

1 Comment

var is a keyword, and it will throw a error when you try to run this code variable name is missing
3

This is because getB is an async function and does not return a B object but a Promise object that have no action method. This promise will further be resolved with a B object and you can access to the resolved value by catching it with the then method as proposed by PVermeer.

1 Comment

Thanks for clarifying that. I was just about to make an edit :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.