-
Notifications
You must be signed in to change notification settings - Fork 640
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
字节:输出以下代码运行结果,为什么?如果希望每隔 1s 输出一个结果,应该如何改造?注意不可改动 square 方法 #69
Comments
原因:使用 如果我们希望每隔
解法一:for 循环async function test() {
for(let i = 0; i<list.length; i++) {
const res = await square(list[i])
console.log(res)
}
}
test() 解法二:for…in / for…of
async function test() {
for(let i in list) {
const res = await square(list[i])
console.log(res)
}
}
test()
async function test() {
for(let x of list) {
const res = await square(x)
console.log(res)
}
}
test() 解法三:利用 promise 的链式调用function test() {
let promise = Promise.resolve()
list.forEach(x=> {
promise = promise.then(() => square(x)).then(console.log)
})
}
test() |
运行结果:一秒后输出1,4,9 原因:在forEach里面写的callback函数会直接在while循环里面调用 改造:用for...of 或者for循环代替 forEach async function test () {
for(let x of list) {
var res = await square(x)
console.log(res)
}
} 贴一下forEach的源码 if (!Array.prototype.forEach) {
Array.prototype.forEach = function(callback, thisArg) {
var T, k;
if (this == null) {
throw new TypeError(' this is null or not defined');
}
var O = Object(this);
var len = O.length >>> 0;
if (typeof callback !== "function") {
throw new TypeError(callback + ' is not a function');
}
if (arguments.length > 1) {
T = thisArg;
}
k = 0;
while (k < len) {
var kValue;
if (k in O) {
kValue = O[k];
callback.call(T, kValue, k, O);
}
k++;
}
};
} |
运行结果,直接输出1 4 9 async function test() {
for await (const x of list) {
const res =await square(x)
console.log(res)
}
}
test() 遍历异步的循环 |
运行结果,直接输出1 4 9 const list = [1, 2, 3]
const square = num => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(num * num)
}, 1000)
})
}
async function test(index = 0) {
const res = await square(list[index])
console.log(res)
if (list[++index]) {
test(index)
}
}
test() |
This was referenced Jul 21, 2020
|
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The text was updated successfully, but these errors were encountered: