首页 > 解决方案 > 即使在 array.Array 中推入元素之后,循环外也显示为空

问题描述

我正在尝试在 node.js 应用程序中使用 cloudinary 上传多个图像。将每个图像 URL 存储在一个数组中。但是我的数组在循环外是空的。无法理解为什么。

const postCreate = (req,res,next) => {
    req.body.post.images = [];
    const file_length = req.files.length;
    let arr = [];
    //console.log(req.files);
    new Promise((resolve, reject) => {
        req.files.forEach((file,index) => {
            i = index;
            cloudinary.v2.uploader.upload(file.path)
                .then(image => {
                    //console.log(image);
                    req.body.post.images.push({
                        url: image.secure_url,
                        public_id: image.public_id
                    });
                    console.log("array", req.body.post.images);//there array is containing the element which is pushed.
                });
            console.log("arr", req.body.post.images);//but there it is showing empty array .Can't understand why array is empty.
        });
        resolve();
    }).then(() => {
            Post.create(req.body.post)
                .then(post => {
                 //console.log(req.body.post.images);
                    res.redirect(`/posts/${post.id}`);
                }).catch(err => {
                    console.log('Error will saving posts from db ', err);
                    return next(err);
                });
    });

标签: javascriptarraysnode.js

解决方案


第二条日志消息实际上在数组为空时首先被调用,因为 then 块中的代码正在等待异步完成。


推荐阅读