Node.js脚本似乎是同步的,即使我希望它是异步的吗?

时间:2018-04-29 21:01:31

标签: javascript python node.js flask

我正在做一个Node.js练习(来自Nodeschool.io),内容如下:

 # LEARN YOU THE NODE.JS FOR MUCH WIN!  

 ## JUGGLING ASYNC (Exercise 9 of 13)  

  This problem is the same as the previous problem (HTTP COLLECT) in that  
  you need to use http.get(). However, this time you will be provided with  
  three URLs as the first three command-line arguments.  

  You must collect the complete content provided to you by each of the URLs  
  and print it to the console (stdout). You don't need to print out the  
  length, just the data as a String; one line per URL. The catch is that you  
  must print them out in the same order as the URLs are provided to you as  
  command-line arguments.  

为了测试我的实现,我制作了一个类似于Flask的小应用程序:

from flask import Flask
import time

app = Flask(__name__)


@app.route("/1")
def hello1():
    time.sleep(1)
    return "Hello 1! "


@app.route("/2")
def hello2():
    time.sleep(0.5)
    return "Hello 2!"


@app.route("/3")
def hello3():
    return "Hello 3!"

为了让我开始进行Nodeschool练习,我编写了以下Javascript代码(jugglingAsync.js):

var http = require('http');
var bl = require('bl');

var handler = (response) => {
    response.pipe(bl(function (err, data) {
    if (err) {
        return console.error(err)
    }
    console.log(data.toString())
    }))
}

http.get(process.argv[2], handler)
http.get(process.argv[3], handler)
http.get(process.argv[4], handler)

但是,如果我运行此脚本,我会看到按顺序打印的响应1-3,而不是相反的顺序:

Kurts-MacBook-Pro:learnyounode kurtpeek$ node jugglingAsync.js http://localhost:5000/1 http://localhost:5000/2 http://localhost:5000/3
Hello 1! 
Hello 2!
Hello 3!

但是,如果这些命令是异步运行的,我实际上希望以相反的顺序打印结果。有人可以解释为什么不是这样吗?

1 个答案:

答案 0 :(得分:0)

事实证明Theodor B是正确的:默认情况下,Flask的底层Werkzeug服务器在单个线程中运行,并且一次只能处理一个请求。为了运行多线程,必须将threaded=True传递给app.run()(参见http://werkzeug.pocoo.org/docs/0.14/serving/#werkzeug.serving.run_simple):

if __name__ == "__main__":
    app.run(threaded=True)

现在,Node.js脚本打印出预期的输出:

Kurts-MacBook-Pro:learnyounode kurtpeek$ node jugglingAsync.js http://localhost:5000/1 http://localhost:5000/2 http://localhost:5000/3
Hello 3!
Hello 2!
Hello 1!