今天就跟大家聊聊有关怎么在es6中使用Async函数,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。
栗子一:
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); } })();
栗子二:根据电影文件名,自动下载对应的海报
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('=== 获取海报完成 ==='); })();
看完上述内容,你们对怎么在es6中使用Async函数有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。