首页 > 解决方案 > JS async/await 使用链接填充数组,然后在填充数组后下载

问题描述

我知道它已被多次询问,但我仍然无法找到解决我的特定问题的方法。基本上按照标题,我编写了一个函数,该函数将通过来自SG Gov Traffic Data API的api 调用getLinks()填充全局数组。links

当我尝试通过函数下载图像时会出现问题,getImages()因为该函数需要等待links数组在运行前被填充。我似乎无法为函数的顺序执行获得正确的逻辑。

完整代码如下。提前感谢您的任何指点!

var fs = require('fs'),
    request = require('request');

// Download individual content
function download(uri, filename, callback){
  request.head(uri, function(err, res, body){
    request(uri).pipe(fs.createWriteStream('training/' + filename)).on('close', callback);
  });
};

// Get image links from API
var links =[];

function two(n){
    return n > 9 ? "" + n: "0" + n;
}

async function getLinks() {
  links = []; // Clear the links array
  for(i = 1; i < 30; i++) { // Loop through 30 days, chosen month is Dec 2018
    for(j = 0; j < 24; j++) { // Loop through 24 hours each day
      request('https://api.data.gov.sg/v1/transport/traffic-images?date_time=2018-12-' + two(i) + 'T' + two(j) + '%3A00%3A00', function(error, response, body) {
        if(!error && response.statusCode == 200) {
          var parsedData = JSON.parse(body);
          links.push(parsedData.items[0]["cameras"][0]["image"].toString())
        } else {
          console.log(error)
        }
      })
    }
  }
  return;
}

// Scrape and download to directory
async function getImages() {
  await getLinks();
  for( i = 0; i < links.length; i++) {
    download(links[i], i, function(){});
  }
}

getImages();

标签: javascriptapipromiseasync-await

解决方案


getLinks 在解决之前返回,

可能在请求调用周围包装一个承诺,将它们推送到一个数组中,然后返回 promise.all(asyncArray)

但目前它只是

async function getImages() {
  await undefined //getLinks();
  for( i = 0; i < links.length; i++) {
    download(links[i], i, function(){});
  }
}

例如:

async function getLinks() {
    links = []; // Clear the links array
    let asyncs = []
    for(i = 1; i < 30; i++) { // Loop through 30 days, chosen month is Dec 2018
      for(j = 0; j < 24; j++) { // Loop through 24 hours each day
        asyncs.push(new Promise((resolve, reject) => {
            request('https://api.data.gov.sg/v1/transport/traffic-images?date_time=2018-12-' + two(i) + 'T' + two(j) + '%3A00%3A00', function(error, response, body) {
            if(!error && response.statusCode == 200) {
                var parsedData = JSON.parse(body);
                links.push(parsedData.items[0]["cameras"][0]["image"].toString())
                resolve(parsedData.items[0]["cameras"][0]["image"].toString())
            } else {
                console.log(error)
                //reject(error)
            }
            })
        }))
      }
    }
    return Promise.all(asyncs)
  }

async function getImages() {
  let _links = await getLinks();
  for( i = 0; i < links.length; i++) {
    download(links[i], i, function(){});
  }
}

推荐阅读