对单线程Node.js的怀疑,其主要目的是节省I / O任务的等待时间

问题描述

我最近了解了node.js架构和事件循环。 Node.js主要基于两件事:

  • 在处理I / O任务时最小化保持时间
  • 避免每个请求创建线程/进程的开销。

我知道node.js通过事件循环来执行此操作,该循环从事件队列中获取一个事件,然后将其提交给某些工作人员,完成后,将通过调用回调来还原。

对于处理I / O以及其他一些耗时的任务非常有用。

但是,如果发生这种情况,那么我想知道如何在node.js中确保代码执行的顺序。

请考虑以下代码段:

// func1 does some very time expensive task

func1(); // does some expensive stuff

func2(); // this requires some varaible in its computation that is updated by func1 and that updated value must be used in func2. But func2 is computationally inexpensive.


// then func2 will complete execution before func1. wont it cause error or hold for func2 ? How is this handled ?

解决方法

您可以使用Promises来确保执行顺序。就像在fun1()中一样。你本可以做这样的事情

function fun1() {
  let promise = new Promise(function(resolve,reject) {
     // Your code goes here
     ..
     // and when you are finished
     resolve(some_value); // some_value could be anything like your variable on which fun2() depends
     // Tip: use reject(error),whenever you encounter an error 
  });
  return promise
}

,当您调用这些函数以确认订单时,请使用此

func1()
  .then(function(some_value) {
    func2()
  },function(error) {
    // handle your errors here
  });