async/await 一般和 Prmoise 一起使用。下面的代码是一个生成 Promise 对象的工具方法。
function doTask({id, success=true,time=100}){
return new Promise(function (resolve, reject) {
setTimeout(function(){// 模拟异步
var msg
if(success) {
msg = `thing ${id} is done`
console.log(msg)
resolve(msg);
} else {
msg = `thing ${id} failed`
console.error(msg)
reject(msg)
}
}, time)
})
}
1.多个串行操作
async function doSerialTing() {
await doTask({id:1})
console.log('sth')
await doTask({id:2, time: 1000})
await doTask({id:3})
}
doSerialTing()
//thing 1 is done
//sth
//thing 2 is done
//thing 3 is done
2.多个并行操作
async function doParallelTing() {
var [res1, res2, res3] = await Promise.all([
doTask( {id:1}),
doTask( {id:2, time: 1000 }),
doTask( {id:3})
])
console.log(res1,res2,res3)
}
doParallelTing()
第一个例子: await只能用在async函数
- 错误示例1:程序不能运行
let funPromise = function (time) {
return new Promise(function (resolve, reject) {
//Pending 进行中
setTimeout(function () {
resolve(); // 从 pending 变为 resolved
}, time);
})
};
let funAsync = async function () {
let numArr = [1003, 1002, 1001];
// 会报错 await没有在async函数中
numArr.forEach(function(value, index){
await funPromise(value);
})
}
funAsync();
- 错误示例2:程序能运行,结果不是我们想要的
let funPromise = function (time) {
return new Promise(function (resolve, reject) {
//Pending 进行中
setTimeout(function () {
// 从 pending 变为 resolved
resolve(time + ' : ' + new Date());
}, time);
})
};
let funAsync = async function () {
let numArr = [1003, 1002, 1001];
numArr.forEach(async function(value, index){
//三个funPromise()操作将是并发执行,也就是同时执行,而不是继发执行
let result = await funPromise(value);
console.log(result);
})
}
funAsync();
- 正确示例
let funPromise = function (time) {
return new Promise(function (resolve, reject) {
//Pending 进行中
setTimeout(function () {
// 从 pending 变为 resolved
resolve(time + ' : ' + new Date());
}, time);
})
};
let funAsync = async function () {
let numArr = [1003, 1002, 1001];
// 三个funPromise()操作将是继发执行
for (let value of number){
let result = await funPromise(value);
console.log(result);
}
}
funAsync();
网友评论