JS异步/等待使用链接填充数组,然后在填充数组后下载

时间:2019-03-15 01:48:18

标签: javascript api promise async-await

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

1 个答案:

答案 0 :(得分:0)

getLinks在解决之前返回,

也许将一个Promise包裹在请求调用周围,将它们推入数组,然后返回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(){});
  }
}