javascript - 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();
解决方案
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(){});
}
}
推荐阅读
- c++ - 为什么 deque 的 pop_front() 和 pop_back() 不是 noexcept?
- mercurial - 如何检查 Mercurial 存储库的一致性(校验和)?
- css - 按下时更改传单簇的样式
- python - PyCharm PEP 8:用于视觉缩进的续行缩进不足
- python - 当项目存储在 NAS 上时 PyCharm 重新索引
- ngxs - 使用子状态测试 NGXS 状态会将错误的状态输入到动作处理程序中
- python - Keras:大小为 x*x 的输入会生成不需要的输出 y*x
- javascript - Codemirror 简单模式 - 正则表达式后视和前瞻不起作用
- html - HTML + CSS:使用图像自定义选项卡或按钮组
- amazon-web-services - API Gateway 流式传输大尺寸内容作为响应