React Native Android-Promise.all为一个promise数组抛出[TypeError:[object Object]不可迭代!]

时间:2018-09-27 09:28:12

标签: reactjs react-native promise react-native-android expo

我正在使用react native和expo。 我有以下代码:

const a = {};
const promises = [];
someArray.forEach(c => {
    a[c] = {
        ref: firebase.ref(`someref/${c}`),
        data: null
    }
    promises.push(new Promise((resolve, reject) => {
       a[c].ref.on('value', (snap) => {
            const data = snap.val() || {};
            // do something with data
            resolve(data);
        },
        (err) => {
            console.error(err)
            return reject(err)
        })
    }))
});

function isIterable(obj) {
    // checks for null and undefined
    if (obj == null) {
        return false;
    }
    return typeof obj[Symbol.iterator] === 'function';
}

console.log(promises)
console.log(isIterable(promises))

Promise.all(promises).then((values)=>{
    console.log("promise all values", values)
}).catch(e=>{
    console.error("promise all failed",e)
})

在Android上运行时出现此错误promise all failed TypeError: [object Object] is not iterable!它在iOS和远程调试JS模式下都可以正常运行console.log(promises)的结果是

Array [
   Promise {
     "_a": undefined,
     "_c": Array [],
     "_d": false,
     "_h": 0,
     "_n": false,
    "_s": 0,
    "_v": undefined,
   },
 ]

奇怪的是console.log(isIterable(promises))的印刷品false

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

显然,Android上的本地本机不支持es6符号。 找到了解决方法here

if (Platform.OS === 'android') {
  if (typeof Symbol === 'undefined') {
    console.log('Polyfilling Symbol on Android');
    require('es6-symbol/implement');
    console.log('Polyfilling Array.prototype[Symbol.iterator] on Android');
    if (Array.prototype[Symbol.iterator] === undefined) {
      Array.prototype[Symbol.iterator] = function() {
        let i = 0;
        return {
          next: () => ({
            done: i >= this.length,
            value: this[i++],
          }),
        };
      };
    }
  }
}