【问题标题】:nodejs array items are Promise "{ <pending> }"nodejs 数组项是 Promise "{ <pending> }"
【发布时间】:2021-09-08 11:30:15
【问题描述】:

我想下载图片。所以我需要异步过程。我的代码被剪成这样:

 Template.findOne({ templateId: template_id }).exec()
        .then(template => {
            if (imageURLs.length !== template.requiredImages.count) {
                res.status(422).json({
                    status: "Fail",
                    message: "This template needed " + template.requiredImages.count + " image. But received " + imageURLs.length
                })
            } else {
                return template;
            }
        })
        .then(template => {

            function naming(length) {
                var result = '';
                var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
                var charactersLength = characters.length;
                for (var i = 0; i < length; i++) {
                    result += characters.charAt(Math.floor(Math.random() *
                        charactersLength));
                }
                return result;
            }
            var download = function (uri, filename, callback) {
                request.head(uri, function (err, res, body) {
                    console.log('content-type:', res.headers['content-type']);
                    console.log('content-length:', res.headers['content-length']);

                    request(uri).pipe(fs.createWriteStream(filename + '.' + res.headers['content-type'].split('/')[1])).on('close', callback);
                });
            };


            var imagePaths = [];

            for (const imageURL of imageURLs) {
                imagePaths.push(new Promise((resolve, reject) => {
                    let filename = __dirname + '/../../../downloads/' + naming(6)
                    download(imageURL, filename, function (data, err) {
                        if (err) reject(err);
                        else resolve(filename)
                    });
                }))

            }

            console.log(imagePaths); ============>>>>> Error Line

            res.json("oki");
        })

我需要等待进程的循环完成。但我的输出是这样的:

[承诺{},承诺{},承诺{}

我该如何解决这个问题?请帮忙!

【问题讨论】:

    标签: javascript node.js asynchronous async-await


    【解决方案1】:

    你只需要用Promise.all解决数组中的所有promise

    Promise.all(imagePaths).then(() => {
      res.json("oki")
    });
    

    【讨论】:

      猜你喜欢
      • 2018-11-16
      • 1970-01-01
      • 2019-05-10
      • 2020-11-17
      • 2018-08-19
      • 2019-12-23
      • 2020-07-09
      • 2017-10-16
      • 1970-01-01
      相关资源
      最近更新 更多