async
async/await
function testAwait(){
return new Promise((resolve) => {
setTimeout(function(){
console.log("testAwait");
resolve();
}, 1000);
});
}
async function helloAsync(){
await testAwait();
console.log("helloAsync");
}
function testAwait(){
setTimeout(function(){
console.log("testAwait");
}, 5000);
}
async function helloAsync(){
await testAwait();
console.log("helloAsync");
}
async/await并行/串行触发
function testAwait1(){
return new Promise((resolve) => {
setTimeout(function(){
console.log("testAwait1");
resolve();
}, 1000);
});
}
function testAwait2(){
return new Promise((resolve) => {
setTimeout(function(){
console.log("testAwait2");
resolve();
}, 1000);
});
}
async function test(){
console.time("testTime")
let pramiseFn1 = testAwait1();
let pramiseFn2 = testAwait2();
let res1 = await pramiseFn1;
let res2 = await pramiseFn2;
console.log("两个promise并行执行,done");
console.timeEnd("testTime")
}
async function test1(){
console.time("test1Time")
let res1 = await testAwait1();
let res2 = await testAwait2();
console.log("两个promise串行执行,done");
console.timeEnd("test1Time")
}
async/await在for循环中使用
function testAwait(id){
return new Promise((resolve) => {
setTimeout(function(){
console.log("testAwait"+id);
resolve(id);
}, 1000);
});
}
async function test(){
console.time('start')
let List = [1,2,3]
let promises = List.map(id=>testAwait(id))
for(let promise of promises) {
let res = await promise
console.log("promise结果:",res)
}
console.log("for循环promise,done")
console.timeEnd('start')
}
test()
async/await捕获异常
function testPromise(){}
async testAsync() {
try {
await testPromise()
} catch(err) {
console.log(err)
}
}
async/await与Generator
function* generatorFn() {
yield '11111111';
yield '22222222';
return '33333333';
}
let test = generatorFn();
test.next();
test.next();
test.next();
test.next();
Promise
var promise = new Promise(function (resolve, reject) {
var a = 1
if (a === 1) {
resolve(a)
} else {
reject(error)
}
})
promise.then(function (value) {
console.log(value++)
return value
}).catch(function (error) {
console.log(error)
}).then(function (value) {
console.log(value++)
})