小编Zee*_*een的帖子

使用 async/await 时调用堆栈的工作

使用 async/await 函数时调用堆栈的行为如何?


function resolveAfter2Seconds() { // taken from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function
  return new Promise(resolve => {
    setTimeout(() => {
      resolve('resolved');
    }, 2000);
  });
}

const asyncFuntion=async()=>{
  const result = await resolveAfter2Seconds();
  console.info("asyncFuntion finish, result is: ", result);
}

const first = async()=>{
    await asyncFuntion();
    console.log('first completed');
        debugger;
}

const second = ()=>{
    console.log('second completed');
        debugger;
}

function main(){
    first();
    second();
}


main();

Run Code Online (Sandbox Code Playgroud)

在上面的代码中,当在 second() 中遇到第一个断点时,我可以看到调用堆栈包含 main() 和 second()。在 first() 的第二个断点期间,调用堆栈包含 main() 和 first()。

在第一个断点期间 first() 发生了什么。它被推到哪里去了?假设 asyncFunction() 需要一些时间才能完成。

有人请帮忙。

javascript event-loop promise ecmascript-6

8
推荐指数
1
解决办法
3311
查看次数

Node Express 不处理并行请求

我刚刚创建了一个 NodeJS Express 服务器来了解 NodeJS 的工作原理。我了解到 NodeJS 可以同时处理大量 API 请求,因为 CPU 密集型任务不是由同一线程完成的。

然而,我的服务器甚至无法同时处理 2 个请求,即使没有任何 CPU 密集型任务也是如此。我很确定我在这里遗漏了一些东西。这是我的代码:

const http = require('http');
const express = require('express');
const app = express();

const waitForSomeTime = () => new Promise((resolve) => {
  setTimeout(() => resolve(), 5000);
});

app.use(async (req, res) => {
  console.log('Request received');
  await waitForSomeTime();
  console.log('Response sending')
  return res.send('DONE');
})

app.set('port', 3000);

const server = http.createServer(app);

server.listen(3000, () => { });
Run Code Online (Sandbox Code Playgroud)

目前,当我并行使用 2 个请求访问 API 时,服务器会在 5 秒后解析第一个请求,然后接受第二个请求。总时间为 10 秒。我在本地 Mac 系统和具有 4 …

javascript asynchronous node.js express server

4
推荐指数
1
解决办法
1491
查看次数