一、async,await用法
await后面接promise对象,并且resolve。
或者接基本类型,如 await 400,会转换为promise对象,并且 resolve(400)
function getSomeThing(){
return new Promise((resolve,reject)=>{
setTimeout(()=>{
resolve('获取成功')
},3000)
})
}
async function getDate(){
const res1 = await getSomeThing("./a.json")
console.log(res1)
const res2 = await getSomeThing("./b.json")
console.log(res2)
const res3 = await getSomeThing("./c.json")
console.log(res3)
}
function call(){
console.log('call funtion');
return new Promise(resolve=>{
setTimeout(function(){
console.log('call funtion timeout');
resolve('dd');
},1000);
});
}
function normalFunction() {
console.log('normalFunction');
return 'data'
}
// call(function(){
// console.log('callback');
// });
async function asynctest() {
console.log('start');
await call();
await normalFunction();
await new Promise(resolve=>{ console.log('wait result'); resolve()});
console.log('end');
}
asynctest();
执行结果:
start
call funtion
call funtion timeout
normalFunction
wait result
end
二、* 函数, yield和next()用法
参考例子:https://zhuanlan.zhihu.com/p/31742488
yield是JS为了解决异步调用的命令。表示程序执行到这里会交出执行权,等待结果返回。它需要在协程Generator 函数中运行。
上面代码中,调用 Generator 函数,会返回一个内部指针(即遍历器g 。这是 Generator 函数不同于普通函数的另一个地方,即执行它不会返回结果,返回的是指针对象。调用指针 g 的 next 方法,会移动内部指针(即执行异步任务的第一段),指向第一个遇到的 yield 语句,上例是执行到 x + 2 为止。
function call(){
console.log('call funtion');
return new Promise(resolve=>{
setTimeout(function(){
console.log('call funtion timeout');
resolve('dd');
},1000);
});
}
function normalFunction() {
console.log('normalFunction');
return 'data'
}
function* yieldFunc() {
console.log('start');
yield call();
yield normalFunction();
console.log('end');
}
let yieldData=yieldFunc();
let firstData=yieldData.next();
console.log(firstData);
firstData.value.then(function(data){
console.log(data);
});
yieldData.next();
console.log(yieldData);
执行结果:
PS F:\zzj1026\Rnx\testEgg> node .\async.js
start
call funtion
{ value: Promise { <pending> }, done: false }
normalFunction
{}
call funtion timeout
dd
PS F:\zzj1026\Rnx\testEgg>
三、Promise.all()
const promise1 = Promise.resolve(3)
const promise2 = 42
const promise3 = new Promise((resolve, reject) => {
setTimeout(reject, 100, 'foo')
})
Promise.all([promise1, promise2, promise3])
.then((values) => {
console.log(values)
})
.catch((values) => console.log('reject', values))
// expected output: Array [3, 42, "foo"]
本文详细探讨了异步编程中的核心概念,包括async/await的使用方法,Promise.all的功能及应用,以及Generator函数中yield和next()的运作机制。通过实际代码示例,展示了如何在JavaScript中有效处理异步操作,确保代码的执行效率和可读性。
2569

被折叠的 条评论
为什么被折叠?



