即使在数组中推送元素之后.数组在循环外显示为空



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

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

在进入最终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'));
}

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

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

请参阅 https://blog.risingstack.com/mastering-async-await-in-nodejs 以获取您的解决方案

它描述了正确输出的async await

最新更新