使用Axios和Promises循环API调用

Tob*_*oby 2 javascript polling axios

我正在使用Axios进行API调用,对于一个调用,我想继续轮询API,直到得到响应为止。

但是,当我调用此函数时,要比预期更早地解决了诺言。

我在这里调用该函数:

componentDidMount() {
  api.getUser(this.props.user.id)
  .then((response) => {
    console.log(response);
    this.handleSuccess(response.content);
  })
  .catch((error) => {
    this.handleError(error);
  });
}
Run Code Online (Sandbox Code Playgroud)

console.log在第4所显示undefined。该函数会继续轮询并在收到有效数据时停止。

函数本身:

getUser(id, retries = 0) {
  return axios(getRequestConfig)
  .then((res) => {
    if (res.data && res.data.content.status === 200) {
      return Promise.resolve(res.data); // success!
    } else if (retries >= 15) {
      return Promise.reject(res); // failure
    } else {
      // try again after delay
      delay(1000)
      .then(() => {
        return this.getUser(id, retries + 1);
      })
    }
  })
  .catch(err => err);
}
Run Code Online (Sandbox Code Playgroud)

Tho*_*mas 6

我将轮询逻辑扩展为一个单独的函数:

//expects fn() to throw if it failed
//if it runs out of retries, poll() will resolve to an rejected promise, containing the latest error
function poll(fn, retries = Infinity, timeoutBetweenAttempts = 1000){
    return Promise.resolve()
        .then( fn )
        .catch(function retry(err){
            if(retries-- > 0)
                return delay( timeoutBetweenAttempts )
                    .then( fn )
                    .catch( retry );
            throw err;
        });
}



getUser(id) {
    function validate(res){
        if(!res.data || res.data.content.status !== 200) 
            throw res; 
    }
    return poll(() => axios(getRequestConfig).then(validate), 15, 1000);
}
Run Code Online (Sandbox Code Playgroud)