数组值未在Node.js中的for循环中更新

时间:2019-04-11 06:57:37

标签: javascript node.js promise es6-promise

从下载功能下载图像后,我试图将数据推送到数组中。这是nodejs承诺中的问题。我该如何解决这个问题。

当前输出:

[
    {
        sku: 99104942591,
        retailer: 'JCREWFCT',
        images: []
    }
]

预期输出:

[
    {
        sku: 99103497136,
        retailer: 'JCREWFCT',
        images: [
            "http://localhost:4001/JCREWFCT/99103497136.png",
            "http://localhost:4001/JCREWFCT/99103497136_1.png"
        ]
    }
]

outputArr中,我正在尝试存储数据

 var downloadImages = async function() {
  var outputArr = [];
  for(var i=0; i<excelJsonArr.length; i++) {
    var d = excelJsonArr[i];
    var out = {
      sku : d.sku,
      retailer : d.retailer,
      images : []
    }
    if(d.image_link_1) {
      var saveDir = path.join('./public', d.retailer, d.sku+'.png');
      var imgUrl = properties.get('protocol') + '://' + properties.get('hostname') + ':' + properties.get('port') + '/' + d.retailer + '/' + d.sku + '.png';
      await download(d.image_link_1, saveDir, function(){
        out.images.push(imgUrl);
      });
    }

    if(d.image_link_2) {
      var saveDir = path.join('./public', d.retailer, d.sku+'_2.png');
      await download(d.image_link_1, saveDir, function(){
        var imgUrl = properties.get('protocol') + '://' + properties.get('hostname') + ':' + properties.get('port') + '/' + d.retailer + '/' + d.sku + '_2.png';
        out.images.push(imgUrl);
      });
    }

    outputArr.push(out);
  }
  console.log(outputArr);
}

var download = async function(uri, filename, callback){
  await 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)).on('close', callback);
  });
};

2 个答案:

答案 0 :(得分:1)

我不知道您的下载功能实际上在做什么,但通常,在使用asnyc时,您会这样做:

2

我应该尝试使用await download(d.image_link_1, saveDir); out.images.push(imgUrl); 来解决try的下载错误,请参见:Correct Try…Catch Syntax Using Async/Await

FYI,下次,分享更多的代码,并在可能的情况下分享可重现的代码或示例GitHub存储库,这样我们就可以自行查看错误。

答案 1 :(得分:1)

由于您使用的是async await,因此不需要使用回调函数。只需在await

之后调用所需的函数
var downloadImages = async function () {
    var outputArr = [];
    for (var i = 0; i < excelJsonArr.length; i++) {
        var d = excelJsonArr[i];
        var out = {
            sku: d.sku,
            retailer: d.retailer,
            images: []
        }
        if (d.image_link_1) {
            var saveDir = path.join('./public', d.retailer, d.sku + '.png');
            var imgUrl = properties.get('protocol') + '://' + properties.get('hostname') + ':' + properties
                .get('port') + '/' + d.retailer + '/' + d.sku + '.png';
            await download(d.image_link_1, saveDir, function () {
                // out.images.push(imgUrl);// <-- not here
            });
            out.images.push(imgUrl); // <-- here
        }

        if (d.image_link_2) {
            var saveDir = path.join('./public', d.retailer, d.sku + '_2.png');
            await download(d.image_link_1, saveDir, function () {
                /* var imgUrl = properties.get('protocol') + '://' + properties.get('hostname') + ':' +
                    properties.get('port') + '/' + d.retailer + '/' + d.sku + '_2.png';
                out.images.push(imgUrl); */ // <-- not here
            });
            var imgUrl = properties.get('protocol') + '://' + properties.get('hostname') + ':' +
                properties.get('port') + '/' + d.retailer + '/' + d.sku + '_2.png';
            out.images.push(imgUrl);  // <-- here
        }

        outputArr.push(out);
    }
    console.log(outputArr);
}