即使在推入数组中的元素之后,数组在循环外仍显示为空

时间:2019-03-24 13:07:42

标签: javascript arrays node.js

我正在尝试在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);
                });
    });

3 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

每个上传都是异步的,并返回一个承诺。

在进行最后的then()

之前,您需要解决所有这些诺言。

您可以映射这些承诺的数组,然后使用Promise.all()将整个数组返回到最终的then()

类似的东西:

const doUpload = (file) => {
  // return the upload promise
  return cloudinary.v2.uploader.upload(file.path).then(image => {
      return {
        url: image.secure_url,
        public_id: image.public_id
      };
    });
}

const postCreate = (req, res, next) => {
  // map array of individual upload promises
  const uploadPromises = req.files.map(doUpload);

  Promise.all(uploadPromises).then(imagesArray => {
    // assign new array to post body
    req.body.post.images = imagesArray;

    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);
      });
  }).catch(err=> console.log('One of the uploads failed'));

}

答案 2 :(得分:0)

您的问题是您的打印函数在循环执行之前就被触发,因此您必须使用async-await以获得正确的解决方案,并了解有关此主题的更多信息

  

请参考https://blog.risingstack.com/mastering-async-await-in-nodejs获得解决方案

它为您的正确输出描述了async await