var ary1 = [] var ary2 = [] function fn1(num){ return new Promise((resolve,reject)=>{ var a = 1 var res1 = 0 var res2 = 0 res1 = a+num setTimeout(()=>{ res2 = a+num resolve(res2) },200) // resolve(res1) }) } //同步 async function fn2(){ for(var i=1;i<4;i++){ var c = await fn1(i) ary1.push(c) } console.log(ary1) } //异步 function fn3(){ for(var i=1;i<4;i++){ fn1(i).then((data)=>{ ary2.push(data) }) } console.log(ary2) } fn2() fn3() // [] // [2, 3, 4] //始终都是空数组先输出,而且点开数组内是有数据的,并且输出的length为0 //如果同步中不加await就会得到promise实力对象,并不能直接使用 //[Promise, Promise, Promise] //__proto__: Promise // [[PromiseState]]: "fulfilled" // [[PromiseResult]]: 2
//异步 function fn4(){ for(var i=1;i<4;i++){ var res = fn1(i).then((data)=>{ console.log(data) return data }) ary2.push(res) } console.log(ary2) } fn4() // [Promise, Promise, Promise] // 2 // 3 // 4 // 虽然输出的data为数字值,但在then中return的data依然是promise实例