[英]waiting for the the function to finish before returning a promise
someFunction() {
if (array.length > 0) {
return new Promise((resolve, reject) => {
array.map(item => {
AXIOS.postItem(item).catch(err => {reject('error')});
});
resolve('resolve');
});
}
}
mainFunction() {
Promise.all([this.someFunction()]).then(() => {
this.invokeTheRest();
)}
}
In my case, the some function always returns resolve
, even before the AXIOS.postItem()
is executed or caught. 在我的情况下,即使在执行或捕获
AXIOS.postItem()
之前,some函数也总是返回resolve
。
How could i wait for the AXIOS.postItem()
to execute? 我如何等待
AXIOS.postItem()
执行? And if there is error caught in catch
how could i NOT proceed to this.invokeTheRest()
? 并且如果在
catch
中catch
了错误,我怎么不能继续进行this.invokeTheRest()
?
Change the body of someFunction to just: 将someFunction的主体更改为:
someFunction () {
return array.map(item => AXIOS.postItem(item));
}
So that it returns an array of Promises that can be used with Promise.all . 以便它返回可与Promise.all一起使用的Promises数组。
Having someFunction return an array of promises I would say is a coding anti-pattern. 让someFunction返回一个promise数组,我会说这是一个编码反模式。
The way I would go is to return the Promise.all from someFunction, this will then make someFunction into a Promise, that you can then use just like any other promise. 我要走的方法是从someFunction返回Promise.all,这将使someFunction成为Promise,然后您就可以像其他任何Promise一样使用它。
eg. 例如。
someFunction() {
return Promise.all(
array.map(item => AXIOS.postItem(item)));
}
mainFunction() {
this.someFunction().then(() => {
this.invokeTheRest();
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.