-
Notifications
You must be signed in to change notification settings - Fork 3.3k
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
第 130 题:输出以下代码执行结果,大致时间就好(不同于上题) #253
Comments
30s |
30s多点 |
30s多一点 |
先说结果,大概30秒多点,30秒是因为每个等待10秒,同步执行。 function wait() {
return new Promise(resolve =>
setTimeout(resolve, 10 * 1000)
)
}
async function main() {
console.time();
let a = wait();
let b = wait();
let c = wait();
await a;
await b;
await c;
console.timeEnd();
}
main(); 这个的运行时间是10s多一点,这是因为:a,b,c的异步请求会按顺序发起。而这个过程是不需要互相依赖等待的。等到wait的时候,其实是比较那个异步耗时最多。就会等待最长。最长的耗时就是整体的耗时。 如果在业务中,两个异步没有依赖关系。应该是后面这种写法。 |
这道题可以这样看执行顺序和每一步消耗的时间: function wait() {
return new Promise(resolve =>
setTimeout(resolve, 10 * 1000)
)
}
async function main() {
console.time('ALL:');
console.time('A:')
await wait();
console.timeEnd('A:');
console.time('B:');
await wait();
console.timeEnd('B:');
console.time('C:');
await wait();
console.timeEnd('C:');
console.timeEnd('ALL:');
}
main(); 打印的结果为: |
|
function wait() {
return new Promise(resolve =>
setTimeout(resolve, 10 * 1000)
)
}
async function main() {
console.time();
await wait();
await wait();
await wait();
console.timeEnd();
}
main();
// Promise {<pending>}
// default: 30001.47412109375ms
function wait() {
return new Promise(resolve =>
setTimeout(resolve, 10 * 1000)
)
}
async function main() {
console.time();
let a = wait();
let b = wait();
let c = wait();
await a;
await b;
await c;
console.timeEnd();
}
main();
// Promise {<pending>}
// default: 10004.033203125ms |
30s多一点,因为js执行不会立刻执行setTimeout,而是有等待其他代码的执行。 |
function wait() { async function main() { 这个怎么解释??? |
The text was updated successfully, but these errors were encountered: