async和await
Async/Await应该是最简单的异步解决方案了。举个例子,写个暂停功能:
var sleep = function (time) {
return new Promise(function (resolve, reject) {
setTimeout(function () {
resolve();
}, time);
})
};
var start = async function () {
// 看起来就像同步代码
console.log('start');
await sleep(3000);
console.log('end');
};
start();
控制台先输出start,稍等3秒后,输出了end。
代码
/**
* Created by salamander on 2016/9/21.
*/
let request = require('request');
let url = "http://localhost/index.php";
let concurrency = 100;
function testLocal() {
return new Promise((resolve, reject) => {
request(url, function (error, response, body) {
if (!error && response.statusCode == 200) {
resolve();
} else {
reject(error);
}
});
});
}
async function testConcurrency() {
for(let i = 0; i < 100; i++) {
try {
let tasks = [];
for(let j = 0; j < concurrency; j++) {
tasks.push(testLocal())
}
await Promise.all(tasks);
console.log('request success ' + i);
} catch(error) {
console.log('request failed');
}
}
}
testConcurrency();
说明
concurrency量可以设置并发请求次数