草庐IT

javascript - 我们可以强制函数调用完成并返回,然后再继续执行 node.js 中的下一条语句吗?

coder 2023-11-08 原文

这里我有一个简单的 HTTP 服务器。当 foo() 被调用时,它会根据键获取一个值。但事实证明,当 foo(key, redisClient) 被调用时,它打印了

I am inside foo

然后马上去汇报

x is null

此时异步redis.get调用结束,现在我明白了

About to return from foo with result: 1

这是我期望的值。但现在我的错误检查已经结束,它已经在 HTTP 响应中写入了错误。在主服务器线程中继续执行任何其他操作之前,我如何确保从 foo() 中实际获得正确的返回值以存储到 x 中?

var http = require('http');
var redis = require("redis");
http.createServer(function (req, res) {

    var x = null;
    var key = "key";
    var redisClient = redis.createClient();

    x = foo(key, redisClient);

    if(x == null)
    {
        // report error and quit
                console.log('x is null');
                // write error message and status in HTTP response
    }
    // proceed
        console.log('Proceeding...');
        // do some stuff using the value returned by foo to var x
        // .........
        // .........
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello World\n');
}).listen(1400, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1400/');


function foo(key, redisClient)
{
    console.log('I am inside foo');
    redisClient.get(key, function(error, result) {
        if(error) console.log('error:' + error);
        else
            {
                    console.log('About to return from foo with result:' + result);
                    return result;
            }
    }
}

最佳答案

redisClient.get() 调用中的返回不会传递给 foo() 的返回。您需要在回调中将值传回。这是修改代码:

var http = require('http');
var redis = require("redis");
var me = this;
http.createServer(function (req, res) {

    var x = null;
    var key = "key";
    var redisClient = redis.createClient();

    me.foo(key, redisClient, function(err, result) {
       x = result;
       if(x == null)
       {
       // report error and quit
               console.log('x is null');
               // write error message and status in HTTP response
       }
       // proceed
        console.log('Proceeding...');
        // do some stuff using the value returned by foo to var x
        // .........
       // .........
       res.writeHead(200, {'Content-Type': 'text/plain'});
       res.end('Hello World\n');
    });

}).listen(1400, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1400/');


function foo(key, redisClient, callback)
{
  console.log('I am inside foo');
  redisClient.get(key, function(error, result) {
    if(error)  {
        console.log('error:' + error);
        callback (error);
    } else {
        console.log('About to return from foo with result:' + result);
        callback(null, result);
    }
  }
}

关于javascript - 我们可以强制函数调用完成并返回,然后再继续执行 node.js 中的下一条语句吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24374645/

有关javascript - 我们可以强制函数调用完成并返回,然后再继续执行 node.js 中的下一条语句吗?的更多相关文章

  1. ruby - 为什么我可以在 Ruby 中使用 Object#send 访问私有(private)/ protected 方法? - 2

    类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc

  2. ruby-openid:执行发现时未设置@socket - 2

    我在使用omniauth/openid时遇到了一些麻烦。在尝试进行身份验证时,我在日志中发现了这一点:OpenID::FetchingError:Errorfetchinghttps://www.google.com/accounts/o8/.well-known/host-meta?hd=profiles.google.com%2Fmy_username:undefinedmethod`io'fornil:NilClass重要的是undefinedmethodio'fornil:NilClass来自openid/fetchers.rb,在下面的代码片段中:moduleNetclass

  3. ruby - 使用 Vim Rails,您可以创建一个新的迁移文件并一次性打开它吗? - 2

    使用带有Rails插件的vim,您可以创建一个迁移文件,然后一次性打开该文件吗?textmate也可以这样吗? 最佳答案 你可以使用rails.vim然后做类似的事情::Rgeneratemigratonadd_foo_to_bar插件将打开迁移生成的文件,这正是您想要的。我不能代表textmate。 关于ruby-使用VimRails,您可以创建一个新的迁移文件并一次性打开它吗?,我们在StackOverflow上找到一个类似的问题: https://sta

  4. ruby - 为什么 4.1%2 使用 Ruby 返回 0.0999999999999996?但是 4.2%2==0.2 - 2

    为什么4.1%2返回0.0999999999999996?但是4.2%2==0.2。 最佳答案 参见此处:WhatEveryProgrammerShouldKnowAboutFloating-PointArithmetic实数是无限的。计算机使用的位数有限(今天是32位、64位)。因此计算机进行的浮点运算不能代表所有的实数。0.1是这些数字之一。请注意,这不是与Ruby相关的问题,而是与所有编程语言相关的问题,因为它来自计算机表示实数的方式。 关于ruby-为什么4.1%2使用Ruby返

  5. ruby - 我可以使用 Ruby 从 CSV 中删除列吗? - 2

    查看Ruby的CSV库的文档,我非常确定这是可能且简单的。我只需要使用Ruby删除CSV文件的前三列,但我没有成功运行它。 最佳答案 csv_table=CSV.read(file_path_in,:headers=>true)csv_table.delete("header_name")csv_table.to_csv#=>ThenewCSVinstringformat检查CSV::Table文档:http://ruby-doc.org/stdlib-1.9.2/libdoc/csv/rdoc/CSV/Table.html

  6. ruby - 我可以使用 aws-sdk-ruby 在 AWS S3 上使用事务性文件删除/上传吗? - 2

    我发现ActiveRecord::Base.transaction在复杂方法中非常有效。我想知道是否可以在如下事务中从AWSS3上传/删除文件:S3Object.transactiondo#writeintofiles#raiseanexceptionend引发异常后,每个操作都应在S3上回滚。S3Object这可能吗?? 最佳答案 虽然S3API具有批量删除功能,但它不支持事务,因为每个删除操作都可以独立于其他操作成功/失败。该API不提供任何批量上传功能(通过PUT或POST),因此每个上传操作都是通过一个独立的API调用完成的

  7. ruby - Chef 执行非顺序配方 - 2

    我遵循了教程http://gettingstartedwithchef.com/,第1章。我的运行list是"run_list":["recipe[apt]","recipe[phpap]"]我的phpapRecipe默认Recipeinclude_recipe"apache2"include_recipe"build-essential"include_recipe"openssl"include_recipe"mysql::client"include_recipe"mysql::server"include_recipe"php"include_recipe"php::modul

  8. ruby - 检查字符串是否包含散列中的任何键并返回它包含的键的值 - 2

    我有一个包含多个键的散列和一个字符串,该字符串不包含散列中的任何键或包含一个键。h={"k1"=>"v1","k2"=>"v2","k3"=>"v3"}s="thisisanexamplestringthatmightoccurwithakeysomewhereinthestringk1(withspecialcharacterslike(^&*$#@!^&&*))"检查s是否包含h中的任何键的最佳方法是什么,如果包含,则返回它包含的键的值?例如,对于上面的h和s的例子,输出应该是v1。编辑:只有字符串是用户定义的。哈希将始终相同。 最佳答案

  9. ruby - 即使失败也继续进行多主机测试 - 2

    我已经构建了一些serverspec代码来在多个主机上运行一组测试。问题是当任何测试失败时,测试会在当前主机停止。即使测试失败,我也希望它继续在所有主机上运行。Rakefile:namespace:specdotask:all=>hosts.map{|h|'spec:'+h.split('.')[0]}hosts.eachdo|host|begindesc"Runserverspecto#{host}"RSpec::Core::RakeTask.new(host)do|t|ENV['TARGET_HOST']=hostt.pattern="spec/cfengine3/*_spec.r

  10. ruby - 有人可以帮助解释类创建的 post_initialize 回调吗 (Sandi Metz) - 2

    我正在阅读SandiMetz的POODR,并且遇到了一个我不太了解的编码原则。这是代码:classBicycleattr_reader:size,:chain,:tire_sizedefinitialize(args={})@size=args[:size]||1@chain=args[:chain]||2@tire_size=args[:tire_size]||3post_initialize(args)endendclassMountainBike此代码将为其各自的属性输出1,2,3,4,5。我不明白的是查找方法。当一辆山地自行车被实例化时,因为它没有自己的initialize方法

随机推荐