javascript await on multiple chained async functions

心不动则不痛 提交于 2020-05-31 05:45:11

问题


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?


回答1:


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.




回答2:


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());


来源:https://stackoverflow.com/questions/56922317/javascript-await-on-multiple-chained-async-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!