[英]how to call function with async await in React function, so I can get the result by sequentially
so I have this function that try to call antoher multiple functions to get all data from every functions, and I expected to call each of function sequentially. 所以我有这个函数,它试图调用多个函数以从每个函数中获取所有数据,我希望依次调用每个函数。 the problem is I still got the result that the every functions in getAll() not done sequentially.
问题是我仍然得到的结果是getAll()中的每个函数都没有顺序执行。 Anybody know how it should've done?
有人知道应该怎么做吗?
_getALL = async () => {
await this.getA();
await this.getB();
await this.getC();
await this.getD();
}
example one of the functions: 示例功能之一:
getA() {
getUserA.list()
.then((res) => {
const responseData = res.data;
const Datas = responseData.map(b => ({
key: b.id,
name: b.name,
}));
this.setState({ users: Datas });
})
.catch((err) => {
console.log( err);
});
}
I just started to learn using this async/await metode.any help would be appreciate 我刚刚开始学习使用此异步/等待方法。任何帮助将不胜感激
i'm not sure but if your function doesn't have a return when you call this one, this await nothing so it continue the script execution. 我不确定,但是如果您的函数在调用此函数时没有返回,则此函数将等待脚本执行。 Try to return something.
尝试退货。
await
will only work with functions that return a promise. await
只能与返回承诺的函数一起使用。 Your getA
function currently returns nothing, ie undefined
. 您的
getA
函数当前不返回任何内容,即undefined
。 You can fix this by adding a return
, like this: 您可以通过添加
return
来解决此问题,如下所示:
getA() {
return getUserA.list()
.then((res) => {
const responseData = res.data;
const Datas = responseData.map(b => ({
key: b.id,
name: b.name,
}));
this.setState({ users: Datas });
})
.catch((err) => {
console.log( err);
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.