node.js - 请求太多会导致nodejs出错吗?

标签 node.js

var urlArr = {
    //ex url_for_site0 = 'https://www.google.com'
    url_for_site0,
    url_for_site1,
    url_for_site2,
    url_for_site3,
    ...
    url_for_site50
};

urlArr.forEach(function(url, index) {
    request(url, function(err, res, body) {
        if(err) console.log(index+err);
        else console.log(index+" success");
    });
});

每次执行应用程序时,我都会得到不同的无序结果和错误。

示例:

1 error : socket hang out
21 error : socket hang out
17 error : socket hang out
1 error : socket hang out
19 error : socket hang out
...(omission)
5 success
15 success
45 success
50 success
11 success
37 success

每次我得到结果时,它们的顺序都是不同的。 这是因为我同时调用了太多请求吗? 当我一一请求时,没有错误。

示例:

request(url_for_site0)
and restart program
request(url_for_site1)
and restart program
request(url_for_site2)
...

最佳答案

NodeJS 事件全部在单个池中处理,并且具有非阻塞性质。您可以引用下图。

当我尝试调用多个 SQL 查询时,我就遇到过这种情况。当我用C#做的时候,完全没有问题。然而,NodeJS 给了我与你类似的行为。

nodejs

我不确定这是否是解决该问题的最佳方案。不过,以下是我通过 SQL 调用解决问题的方法。我使用了异步 waterfall 函数,使整个过程变得同步。每个函数都将逐个运行,其返回值通过管道传递到下一个函数。所以,你甚至可以做更多的事情。该库的使用不是很简单,您可以引用此链接以更好地帮助您了解异步 waterfall 是如何工作的,然后使其适合您的解决方案。

https://gist.github.com/dineshsprabu/e6c1cf8f2ca100a8f5ae

以下是我如何想象您的解决方案大致如下:

var async = require('async');

async.waterfall(
[
    function(callback) {
        function_urlArr(url, index, function (returnVal) {
            //Do something with the returnVal
            callback(null, returnVal);
        });

    },
    function(returnVal, callback) {
        //the returnVal from first function gets passed here synchronously
        function_urlArr(url2, index2, function (returnVal) {
            //Do something with the returnVal
            callback(null, returnVal);
        });
    },
    function(returnVal, callback) {
        //and so on ...
    }
],
function (err) {
    //console.log(err);
});

//define your function and enable callback
//you will need to include an extra third argument to receive the callback
function urlArr(url, index, callback) {
    //your code
    return callback(returnValue)
}

关于node.js - 请求太多会导致nodejs出错吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49897268/

相关文章:

node.js - 如何获取 Nodejs 中显示的 console.log 行号?

javascript - fns[i](套接字,函数(错误){ TypeError : Property '0' of object [object Object] is not a function in/socket. io/lib/namespace.js:119

node.js - 如何从基于 promise 的 Passport 本地策略中获得值(value)?

javascript - Jest 模拟特定的配置值

javascript - 位置 1 的 JSON 中的意外标记 u

Node.js 在 typeorm 的实体中添加 created_at 和 updated_at

node.js - 如何在docker compose secret中使用主目录中的文件?

node.js - 与 expect.js 设置等价

javascript - 在 Mocha 中使用 Sinon 读取断言控制台消息

javascript - 如何将参数传递给 Node js 中的函数