【问题标题】:Promises in React nativeReact Native 中的 Promise
【发布时间】:2018-12-08 03:13:50
【问题描述】:

api/index.js

const URL = 'http://10.0.2.2:5000';
const fetching = false;

export default (type, filter, dateFilter, position) => {
    if(fetching) return Promise.reject(new Error('Request in progress'));
    fetching = true;
    return fetch(URL + `/search/${type}/${filter}/${dateFilter}/${position}/0/0`)
    .then(response => Promise.all([response, response.json()]))
    .catch(err => console.log("error catch search:", err.message))

}

我需要把 fetching false 这样我就可以再次调用这个函数,但我不知道把它放在哪里让它工作。 如果我在 then writen 之后和 catch 之前创建另一个 then 像这样:

.then(() => fetching = false)

问题是它返回 false 到调用函数的地方,而不是调用这里的数据:

actions/index.js

getDataApi(type, filter, dateFilter, position)
   .then(res => {   
     if (res !== false) {         
         if (state.dataReducer.data.length === 0) {
             dispatch(getDataSuccess(res[1]))
         } else {
             dispatch(getDataSuccess(res[1], state.dataReducer.data))
         }       
    }
 })
.catch((err) => console.log(9999, err))

所以我的问题是它没有进入getDataSuccess,因为它是假的。我不知道为什么它不能将数据发送到这个函数并结束发送fetching = false的结果。

【问题讨论】:

  • const fetching = false; Erm,const,你确定?

标签: javascript reactjs react-native promise


【解决方案1】:

您需要另一个.then,以便在response.json() 解析后重新分配fetching。您还应该在catch 中重新分配fetching,以便即使出现一次错误,将来的请求也是可能的,在catch 中分配return false,因此.then 之后的.then 将正确忽略失败的请求。另外,对于fetching,请使用let 而不是const

const URL = 'http://10.0.2.2:5000';
let fetching = false;

export default (type, filter, dateFilter, position) => {
  if (fetching) return Promise.reject('Request in progress');
  fetching = true;
  return fetch(URL + `/search/${type}/${filter}/${dateFilter}/${position}/0/0`)
    .then(response => Promise.all([response, response.json()]))
    .then(([response, responseObj]) => {
      fetching = false;
      return [response, responseObj];
    })
    .catch(err => {
      console.log("error catch search:", err.message);
      fetching = false;
      // Choose one, depends what you need.
      return false; // If you want to ignore the error and do something in a chained .then()
      return Promise.reject(err); // If you want to handle the error in a chained .catch()
    })
}

【讨论】:

  • 我想知道 TC39 第 4 阶段提案 - Promise#finally 是否也有帮助
猜你喜欢
  • 2020-01-18
  • 2019-07-18
  • 1970-01-01
  • 2016-05-16
  • 1970-01-01
  • 2022-12-22
  • 1970-01-01
  • 1970-01-01
  • 2020-03-07
相关资源
最近更新 更多