简体   繁体   English

在幕后执行异步代码,如 Promises

[英]Execution of asynchronous code like Promises under the hood

How does Node.js (and JavaScript in general) implement the execution of asynchronous code like Promises under the hood? Node.js(以及一般的 JavaScript)如何在幕后实现异步代码(如 Promises)的执行? Does it run a new thread?它运行一个新线程吗? Does it use Worker for that or there is some OS or libuv functionality?它是否使用 Worker 或有一些操作系统或 libuv 功能?

var promise1 = new Promise(function(resolve, reject) { 
    let now = new Date(); 
    while((now - 6000) < start){
        now = new Date();
    }
    resolve(now - start)
});

var promise2 = new Promise(function(resolve, reject) { 
    let now = new Date(); 
    while((now - 6000) < start){
        now = new Date();
    }
    resolve(now - start)
});
let start = new Date(); 
promise1.then(
    function(value) {
      console.log("Promise 1: ", value);
    }
)

promise2.then(
    function(value) {
      let finish = new Date();
      console.log("Promise 2: ", value);
      console.log(finish - start);
    }
)

Promises are not asynchronous in Node.js. Promise 在 Node.js 中不是异步的。 But there is a new feature - Worker that is asynchronous.但是有一个新功能 - Worker 是异步的。 It runs in a separate proccess.它在单独的进程中运行。 So you can use that, here is a bit more info: https://nodejs.org/api/worker_threads.html所以你可以使用它,这里有更多信息: https : //nodejs.org/api/worker_threads.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM