繁体   English   中英

在 javascript 中的异步 function 中推送数组产生空数组或嵌套数组

[英]Push array inside async function in javascript produces empty or nested array

我有一个异步 function 将表单中的多个文件存储到 Firebase 存储中,我想收集文件名,以便在下一步将它们存储在数据库中。

问题是生成的文件名数组有点“嵌套”,当存储到数据库中时 - 该字段为空。 当我在控制台中返回数组时(请参见下图),数组是:

  1. 用 JSON stringify 粘贴则为空(图中绿线)
  2. 是无法保存到数据库的排序的“多级”数组(在列表中作为数组)(图片中的粉红色线)
  3. 数组转换为字符串时为空(图中蓝线)

请建议如何纠正这个问题。 谢谢!

这是我的代码:

var $dbTimestamp = firebase.firestore.Timestamp.now();
var $fileNames = [];

// I use Promise to wait for all names to be pushed to Array
let myPromise = new Promise(function(success){
    success(
        // Function triggers Async function for each file to be uploaded
        $filesForUpload.map(async function(file, index){
            var $fileName = "rfp/rfp" + $dbTimestamp.valueOf().slice(0,12) + (index + 1);
            // Waiting for the upload to complete
            await $storageRef.child($fileName).put(file).then(function(snapshot){
                console.log("200 File upload completed. File(s) " + (index + 1) + "/" + $filesForUpload.length);
                // Here is where I update my array
                $fileNames.push($fileName);
            }).catch(function(error){
                console.error("500 File upload failed. File(s) " + (index + 1) + "/" + $filesForUpload.length, error);
                NotifyServerError();
            });
        })
    );
});
// Once promise is completed, i try to pass list of file names to next function.
myPromise.then(
    function(success){
        UpdateDB($fileNames, $dbTimestamp);
        console.log(JSON.stringify($fileNames));
        console.log($fileNames);
        console.log($fileNames.toString());
    }
);

在此处输入图像描述

  • 您不能在.map().forEach().filter()等方法中await ,但可以在for(... of...)循环中。

  • 在这里使用.map()是没用的,因为它没有返回任何东西。

  • 您正在混合await -style 和.then() -Promise-style,这里只是await样式。

 const $dbTimestamp = firebase.firestore.Timestamp.now(); const $fileNames = []; const myPromise = async() => { for (let file of $filesForUpload) { const $fileName = "rfp/rfp" + $dbTimestamp.valueOf().slice(0, 12) + (index + 1); try { const snapshot = await $storageRef.child($fileName).put(file); console.log("200 File upload completed. File(s) " + (index + 1) + "/" + $filesForUpload.length); // Here is where I update my array $fileNames.push($fileName); } catch (error) { console.error("500 File upload failed. File(s) " + (index + 1) + "/" + $filesForUpload.length, error); NotifyServerError(); } } } ( async () => { await myPromise(); UpdateDB($fileNames, $dbTimestamp); // <- You probably want to await this as well... console.log(JSON.stringify($fileNames)); console.log($fileNames); console.log($fileNames.toString()); })()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM