连锁无极承诺

时间:2018-07-21 20:53:02

标签: javascript reactjs promise google-cloud-functions

我在从连锁Promise获得响应时遇到一些问题。

我有我的组件从链开始的地方

组件

unsigned n = 4 * k;
int v[n];
for (unsigned i = 0; i < k; ++i)
  for (unsigned j = 0; j < 4; ++j)
    v[4 * i + j] = i;

unsigned state = 1;
do {
  /* process the permutation */ 
} while ((state = multipermute_step(v, n, state);

此组件调用我的API帮助器:

  componentDidMount = async ()=> {
    try{
      const products = await post('payments/getProducts', {});
      console.log(products);
    } catch(e) {
      console.log(e)
    }
  }

然后我的API帮助器调用Firebase Cloud函数,该函数调用Stripe:

async function post(url, data) { 
token = null;  
if (firebase.auth().currentUser) {
  token = await firebase.auth().currentUser.getIdToken();
} 
    try {
      const response = axios({
        method: 'POST',
        headers: {
          Authorization: `${token}`,
        },
        data,
        url: `${API_URL}${url}`,
      })
      return response;
    } catch(e){
      Promise.reject(e);
    }
  }

调用该函数没问题,我的Cloud Function注销了产品数据,但是我无法获得登录API Helper或组件的响应。

1 个答案:

答案 0 :(得分:3)

 Promise.reject(e);

这是完全没有意义的,因为它会创建一个新的被拒绝的承诺,该承诺不会在任何地方使用。您可以await将其链接到async function返回的承诺中,也可以只从axios返回承诺:

async function post(url, data) {    
  let token = null; // always declare variables!
  if (firebase.auth().currentUser) {
    token = await firebase.auth().currentUser.getIdToken();
  } 

  return axios({
    method: 'POST',
    headers: {
      Authorization: `${token}`,
    },
    data,
    url: `${API_URL}${url}`,
  });
}

现在错误不再消失,您可能可以调试问题了:)

相关问题