【问题标题】:TypeError: #<Promise> is not iterableTypeError: #<Promise> 不可迭代
【发布时间】:2019-04-01 22:39:31
【问题描述】:

我试图使用 promise.all 进行多个 api 调用,但由于某种原因它抛出了以下错误

TypeError: # is not iterable

我的 Promise 相当简单(这可能是我第二次使用 Promise.all)

componentWillMount() {
    const id = this.props.location.pathname
    let axiosHome = axios.get('/home')
    let axiosUserData = axios.get("/profile/" + id)
    Promise.all(axiosHome,  axiosUserData).then(response => {
        console.log(response)
    }).catch(error => {
        console.log(error)
    })
  }

问题:知道为什么我会收到此错误吗?另外,有人能解释一下我们什么时候用resolve关键字和promise吗?

【问题讨论】:

    标签: javascript ajax reactjs promise es6-promise


    【解决方案1】:

    Promise.all 接受单个参数,它是一个 Promises 的数组 - 随后的参数被丢弃。所以,改为传入一个数组:

    Promise.all([axiosHome,  axiosUserData])
      .then(...
    

    什么时候我们将 resolve 关键字与 promise 一起使用?

    resolve 不是关键字,它只是构造Promise 时使用的常规函数​​名称:

    const prom = new Promise((resolve, reject) => {
      // do some asynchronous stuff
      if (ok) resolve();
      else reject();
    });
    

    Promise 像这样显式构造时,调用 resolve() 来解决 Promise。 (当然,函数参数可以任意命名,不一定非得叫resolve

    【讨论】:

      【解决方案2】:

      Promise.all() 接受方法数组(异步)并且可以将数据分配给变量 作为数组

      示例:

      let [axiosHomeData , axiosUserData] = await Promise.all([axiosHome,  axiosUserData]);
      

      【讨论】:

        猜你喜欢
        • 2021-08-31
        • 2018-08-06
        • 2021-11-05
        • 2013-09-01
        • 2017-08-27
        • 2018-10-10
        • 2021-12-13
        • 2019-02-20
        • 2020-03-27
        相关资源
        最近更新 更多