node.js - 如何从 Node js 回调返回

标签 node.js

我编写了一个小代码片段,它打印输出,但它没有从回调()返回任何值

你能帮我看看我哪里错了吗? `

function helloworld(string,callback){
  //callback(string){
        if ( string == "Tim"){
          callback('null',string+" "+"Little");
        } else if ( string == "Jason"){
          callback('null',string+"Right") ;
        } else {
          callback ('error : No rule is defined for '+string,string);
        }
    //  };
}


function invoke_callback(input){
      helloworld(input,
          function(err,name){
              if (err != 'null'){
                console.log(err);
                return(err);
              }
              console.log(name);
              return(name);
          }
      )
}

console.log(invoke_callback("Tim"));

`

它的输出是 - 蒂姆·利特尔 未定义

我期待着—— 蒂姆·利特尔 蒂姆·利特尔

最佳答案

你错过了一些东西。最后一个console.log正在打印invoke_callback返回的内容,但什么也没有。这就是未定义的原因。 为了得到你想要的,你必须返回 helloworld 方法的结果。但这个方法也不返回任何东西。所以需要返回回调结果。然后你就会得到它。这是它的样子:

function helloworld(string,callback){
  //callback(string){
        if ( string == "Tim"){
          return callback('null',string+" "+"Little");
        } else if ( string == "Jason"){
          return callback('null',string+"Right") ;
        } else {
          return callback ('error : No rule is defined for '+string,string);
        }
    //  };
}


function invoke_callback(input){
      return helloworld(input,
          function(err,name){
              if (err != 'null'){
                console.log(err);
                return(err);
              }
              console.log(name);
              return(name);
          }
      )
}

console.log(invoke_callback("Tim"));

关于node.js - 如何从 Node js 回调返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48600124/

相关文章:

javascript - Zapier CLI 中触发器的过滤器响应

javascript - 如何将对象中的每个值写入文本文件中的每一行

javascript - 为什么我在 UI 中没有收到验证 Flash 消息,我收到这样的 Flash 错误 [object Object],[object Object],[object Object]

javascript - 如何从nodejs检查Redis缓存连接状态

node.js - DynamoDB 扫描,ExpressionAttributeValues 意外键 NodeJS 中的错误

javascript - Promise.all(...).spread 不是并行运行 Promise 时的函数

javascript - npm cache clean v/s npm cache verify

javascript - Puppeteer 一次打开每个文件的 chrome 实例

node.js - 从容器内服务网格的网站

node.js - Swagger-UI-Express 未在 Azure 应用服务中加载 : 404 Not Found