Javascript 如何在ES6承诺中使用递归?
我想使用axios get请求检查具有新设置id的帖子是否已经存在。(我在前端执行此操作,因为我无法控制后端) 然而,我不知道当一个带有该id的帖子已经存在并且它在承诺中时,如何组合我想要的递归 到目前为止,我得到的是:Javascript 如何在ES6承诺中使用递归?,javascript,recursion,es6-promise,axios,Javascript,Recursion,Es6 Promise,Axios,我想使用axios get请求检查具有新设置id的帖子是否已经存在。(我在前端执行此操作,因为我无法控制后端) 然而,我不知道当一个带有该id的帖子已经存在并且它在承诺中时,如何组合我想要的递归 到目前为止,我得到的是: import axios from 'axios'; import uuidv4 from 'uuid/v4'; export function newPost(post) { return (dispatch) => { getUniqueId.then(
import axios from 'axios';
import uuidv4 from 'uuid/v4';
export function newPost(post) {
return (dispatch) => {
getUniqueId.then((id) => {
// post new post with unique id
// dispatch({ type: NEW_POST_FULFILLED, payload: err });
}).catch((err) => {
dispatch({ type: NEW_POST_FAILED, payload: err });
})
}
}
const getUniqueId = new Promise((resolve, reject) => {
checkUniqueId(resolve, reject, uuidv4())
});
const checkUniqueId = (resolve, reject, id) => {
axios
.get(`${api}/posts/${id}`, { headers })
.then((resp) => checkUniqueId(resolve, reject, uuidv4()))
.catch((err) => {
if(err.response.status === 500) {
resolve(id);
} else {
reject(err);
}
});
}
以下是这一方法的工作原理:
var i=0;
函数newPost(){
getUniqueId().then(函数(id){
log('got it:'+id);
});
}
函数getUniqueId(){
返回checkUniqueId(i).catch(函数(){
log('id'+i+'已在使用中');
i++;
返回getUniqueId();
});
}
函数检查唯一id(id){
返回新承诺(功能(解决、拒绝){
如果(i<2){
拒绝();
}否则{
解决(id);
}
});
}
newPost()代码>一些问题:
getUniqueId
应该是一个函数,因为每次调用newPost
时,您都希望获得一个新id
- 您不应该使用:不要创建新的承诺,而是只返回承诺本身,或者在需要拒绝时抛出
以下是更正后的代码:
export function newPost(post) {
return (dispatch) => {
// Call as function!
getUniqueId().then((id) => {
// post new post with unique id
// dispatch({ type: NEW_POST_FULFILLED, payload: err });
}).catch((err) => {
dispatch({ type: NEW_POST_FAILED, payload: err });
})
}
}
// Define as function, and just return the promise from `checkUniqueId`
const getUniqueId = _ => checkUniqueId(uuidv4());
const checkUniqueId = (id) => {
// return the promise!
return axios
.get(`${api}/posts/${id}`, { headers })
.then((resp) => checkUniqueId(uuidv4()))
.catch((err) => {
if (err.response.status === 500) {
return id;
} else {
throw err; // throw the error to cascade it through the chain
}
});
}
为什么这里需要递归?如果您要检查单个帖子是否存在,那么就不需要递归。另一方面,如果你愿意为一篇不存在的文章生成尽可能多的ID,那是另一种情况。。?