如何在ES6承诺中使用递归?

时间:2017-09-09 10:22:30

标签: 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((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);
      }
    });
}

2 个答案:

答案 0 :(得分:1)

一些问题:

  • getUniqueId应该是一个函数,因为每次调用newPost时都希望获得一个新的id。

  • 您不应该使用promise constructor antipattern:不要创建新的承诺,而只是返回承诺本身,或者当您需要拒绝时throw

    < / LI>

以下是更正后的代码:

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

答案 1 :(得分:0)

以下是这可行的方法:

var i = 0;

function newPost() {
  getUniqueId().then(function(id) {
    console.log('got it: ' + id);
  });
}

function getUniqueId() {
  return checkUniqueId(i).catch(function() {
    console.log('id ' + i + ' is already in use');
    i++;
    return getUniqueId();
  });
}

function checkUniqueId(id) {
  return new Promise(function(resolve, reject) {
    if (i < 2) {
      reject();
    } else {
      resolve(id);
    }
  });
}

newPost();

我重写了一下,以便能够自己测试和理解它,所以希望你能够改变它:)。

相关问题