NodeJS Promise在每个对象数组中处于挂起状态

bttbmeg0  于 2023-06-05  发布在  Node.js
关注(0)|答案(2)|浏览(363)

我想在对象数组中执行promise,并将数组中的路径值替换为我在下面代码中尝试的同一数组中的promise响应:

const cloudinary = require('cloudinary')
const cloudinaryConfig = require('../configs/cloudConfig.json')

cloudinary.config({
    cloud_name: cloudinaryConfig.cloud_name,
    api_key: cloudinaryConfig.api_key,
    api_secret: cloudinaryConfig.api_secret
})

fileArray = [
  {
    fieldname: 'productThumbImage',
    originalname: 'Boyka.png',
    path: '/home/rahul/MaxDigiAssignment/mxNodeEcommerce/mx-ecommercenode/upload/product/1589983049420.png'
  },
  {
    fieldname: 'productPhoto',
    originalname: 'Code.png',
    filename: '1589983049436.png',
    path: '/home/rahul/MaxDigiAssignment/mxNodeEcommerce/mx-ecommercenode/upload/product/1589983049436.png'
  },
  {
    fieldname: 'productPhoto',
    originalname: 'Boyka.png',
    filename: '1589983049438.png',
    path: '/home/rahul/MaxDigiAssignment/mxNodeEcommerce/mx-ecommercenode/upload/product/1589983049438.png'
  }
]

 const files =  imgs.map(async (img)=>{
        let path = await cloudinary.v2.uploader.upload(img.path)
        return {
            ...img,
            filePath: path.url
        }
    })

console.log('files 11///  ',await files);

但我正在获取错误承诺{ }
我想在每个对象中执行这个promise,并得到响应,然后我的预期数组如下所示:

[
  {
    fieldname: 'productThumbImage',
    originalname: 'Boyka.png',
    path:'http://res.cloudinary.com/deqpxepbs/image/upload/v1589982424/ywfetodkvyadmdqjof1i.png'
  },
  {
    fieldname: 'productPhoto',
    originalname: 'Code.png',
    filename: '1589983049436.png',
    path:'http://res.cloudinary.com/deqpxepbs/image/upload/v1589982424/desb18dgungva5y8apbv.png'
  },
  {
    fieldname: 'productPhoto',
    originalname: 'Boyka.png',
    filename: '1589983049438.png',
    path:'http://res.cloudinary.com/deqpxepbs/image/upload/v1589982424/ugud4flh7gfl3ymyh0xx.png'
  }
]
jvidinwx

jvidinwx1#

files将是一个promise数组,它不是一个单一的promise。您应该:

console.log('files 11///  ',await Promise.all(files));
at0kjp5o

at0kjp5o2#

你要做的是:

  • map您的图像数组到Promise s数组
  • await所有的Promise并以路径/URL数组的形式获取结果
  • map对象数组的路径数组。
const getNewFiles = async (imgs) => {
    const promises = imgs.map(img => {
        return cloudinary.v2.uploader.upload(img.path)
    })

    const paths = await Promise.all(promises)
    /* If you're using Node.js version 12 or more recent, a better
       alternative to `Promise.all` is `Promise.allSettled` */
    // const paths = await Promise.allSettled(promises)

    const newFiles = paths.map((path, index) => {
        return {
            ...imgs[index],
            path: path.url
        }
    })

    return newFiles
}

// You can now just pass your `fileArray` to this function as below
const files = await getNewFiles(fileArray)
console.log(files)

相关问题