//下面两种形式的async函数效果相同,await只能用在async函数内部
async function(){}
async () => {}
var http = require('http');
(async () => {
var res = await new Promise(function (resolve, reject) {
var options = {
hostname: 'XXX.com',
path: "/api",
method: 'GET'
};
var req = http.request(options, function (res) {
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('BODY: ' + chunk);
resolve(chunk);
});
});
req.on('error', function (e) {
console.log('problem with request: ' + e.message);
reject(new Error('http failed'));
});
req.end();
});
console.log('request body:' + res);
})();
这里用sequelize作为orm中间件,配置好数据库连接后在函数内:
(async () => {
var Pets = await Pet.findAll({
offset: 0,
limit: 5,
where: { id: 1 }
});
console.log(Pets[0].name);
})();
import fs from 'fs';
import path from 'path';
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)));
});
});
};
(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('=== 获取海报完成 ===');
})();
比如服务器端多个请求可以并发运行,但需要都返回结果后再运行下面的代码,此处也可以是数据库,或者其他耗时回调操作,这里拿数据库操作举例
(async () => {
var petPromise = new Promise(function (resolve, reject) {
Pet.findOne({
where: {
id: 1
}
}).then(function (p) {
resolve(p);
}).catch(function (err) {
reject(new Error('failed: ' + err));
});
});
var perPromise = new Promise(function (resolve, reject) {
Pet.findOne({
where: {
id: 1
}
}).then(function (p) {
resolve(p);
}).catch(function (err) {
reject(new Error('failed: ' + err));
});
});
var argList = await Promise.all([petPromise, perPromise]);
console.log(argList[1].name + 'love' + argList[0].name)})();
})();