等待所有的承诺在forEach循环上解决

时间:2020-05-16 15:59:30

标签: ecmascript-6 promise async-await

整个上午,我一直在撞墙。我有以下代码:

let fold = [{...},{...},{...}] // fold is an array of objects, abbreviated here for simplicity
let track = []
async function getTracks() {
   fold.forEach(async (f, index) => {
      let track = {};
      track.name = f.name;
      track.start = f.start;
      await storageRef
         .child(foldId + "/" + f.filename)
         .getDownloadURL()
         .then((url) => {
             console.log(url); // *
             track.src = url;
         });
      await tracks.push(track);
   });
}
getTracks().then(console.log(tracks)); // **

我希望在track中得到一个对象数组,仅当forEach循环完成时才应将其打印到控制台。相反,我得到以下输出:

Array []
https://firebasestorage.googleapis.com/v0/b/musicfolds.appspot.com/o/L69IkyFyaLHu2KkxgrdL%2F1589059357106
https://firebasestorage.googleapis.com/v0/b/musicfolds.appspot.com/o/L69IkyFyaLHu2KkxgrdL%2F1589059425650
https://firebasestorage.googleapis.com/v0/b/musicfolds.appspot.com/o/L69IkyFyaLHu2KkxgrdL%2F1589553387295
https://firebasestorage.googleapis.com/v0/b/musicfolds.appspot.com/o/L69IkyFyaLHu2KkxgrdL%2F1589059596340
https://firebasestorage.googleapis.com/v0/b/musicfolds.appspot.com/o/L69IkyFyaLHu2KkxgrdL%2F1589570099464

如您所见,在forEach解析url之前,该数组是通过.then指令从**打印到控制台的(它们在*处依次打印,但在之后 .then! 顺便说一句,该数组以一种奇怪的方式打印:它看起来是空的,但是当单击它时(我在firefox上使用,以防万一),结果显示出预期的结果。

如何使forEach循环等待url返回,以便可以用实际值填充数组?

谢谢!

0 个答案:

没有答案