导航
导航
文章目录
  1. async函数栗子
    1. 栗子一:从豆瓣 API 获取数据
    2. 栗子二:根据电影文件名,自动下载对应的海报

读书笔记-es6Async函数栗子

async函数栗子

栗子一:从豆瓣 API 获取数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
var fetchDoubanApi = function() {  
return new Promise((resolve, reject) => {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 300) {
var response;
try {
response = JSON.parse(xhr.responseText);
} catch (e) {
reject(e);
}
if (response) {
resolve(response, xhr.status, xhr);
}
} else {
reject(xhr);
}
}
};
xhr.open('GET', 'https://api.douban.com/v2/user/aisk', true);
xhr.setRequestHeader("Content-Type", "text/plain");
xhr.send(data);
});
};
(async function() {
try {
let result = await fetchDoubanApi();
console.log(result);
} catch (e) {
console.log(e);
}
})();

栗子二:根据电影文件名,自动下载对应的海报

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import fs from 'fs';
import path from 'path';
import request from 'request';
var movieDir = __dirname + '/movies',
exts = ['.mkv', '.avi', '.mp4', '.rm', '.rmvb', '.wmv'];
// 读取文件列表
var readFiles = function () {
return new Promise(function (resolve, reject) {
fs.readdir(movieDir, function (err, files) {
resolve(files.filter((v) => exts.includes(path.parse(v).ext)));
});
});
};
// 获取海报
var getPoster = function (movieName) {
let url = `https://api.douban.com/v2/movie/search?q=${encodeURI(movieName)}`;
return new Promise(function (resolve, reject) {
request({url: url, json: true}, function (error, response, body) {
if (error) return reject(error);
resolve(body.subjects[0].images.large);
})
});
};
// 保存海报
var savePoster = function (movieName, url) {
request.get(url).pipe(fs.createWriteStream(path.join(movieDir, movieName + '.jpg')));
};
(async () => {
let files = await readFiles();
// await只能使用在原生语法
for (var file of files) {
let name = path.parse(file).name;
console.log(`正在获取【${name}】的海报`);
savePoster(name, await getPoster(name));
}
console.log('=== 获取海报完成 ===');
})();
支持一下
谢谢你请我吃糖果