Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/361.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在每个承诺的url中读取数据?_Javascript_Reactjs_Firebase_Firebase Realtime Database_Promise - Fatal编程技术网

Javascript 在每个承诺的url中读取数据?

Javascript 在每个承诺的url中读取数据?,javascript,reactjs,firebase,firebase-realtime-database,promise,Javascript,Reactjs,Firebase,Firebase Realtime Database,Promise,我想用database64字符串替换对象中的firebase子数据图像url。它工作得很好,但我对async有问题吗?我怎么能在我的foreach中等待我所有的价值呢 return FirebaseRef.child('rav').on('value', snapshot => { // const userData = snapshot.val() || []; var obj = { } snapshot.forEach(child =>

我想用database64字符串替换对象中的firebase子数据图像url。它工作得很好,但我对async有问题吗?我怎么能在我的foreach中等待我所有的价值呢

 return FirebaseRef.child('rav').on('value', snapshot => {
    //   const userData = snapshot.val() || [];

    var obj = {

    }

    snapshot.forEach(child => {

      function toDataURL(url, callback) {
        var xhr = new XMLHttpRequest();
        xhr.onload = function () {
          var reader = new FileReader();
          reader.onloadend = function () {
            callback(reader.result);
          }
          reader.readAsDataURL(xhr.response);
        };
        xhr.open('GET', url);
        xhr.responseType = 'blob';
        xhr.send();
      }

      toDataURL(child.val().avatar, function (dataUrl) {
        // console.log('RESULT:', dataUrl)

        obj[child.key] = {

          ...child.val(),
          avatar: dataUrl
        }
        console.log('obj', obj)
      })



    });


    console.log('obj', obj)

    this.updateAvatar({ profile: obj }); // Send to reducer


  });
},

}),在forEach之前创建一个空数组,让
callback()
函数返回一个
Promise.resolve()
,将
callback()
的返回值(Promise)推送到数组中,然后(在forEach之后)使用
Promise.resolve()
使用数组触发所有FileReader()调用完成后要调用的操作。

首先让我声明不应在循环中定义函数。它在循环的每一步都在重新定义。那不是你的问题。幸运的是,我在今年早些时候编写了这样一个函数。此数据URL在wikipedia上找到

函数dataURLtoBlob(dataURL){ 变量d; if(typeof dataURL!='string'| |!((d=dataURL.split('base64'))和&d.length>1)){ 返回false; } var s=atob(decodeURIComponent(d[1]),l=s.length,a=newuint8array(l); 对于(var i=0;i