【问题标题】:Passing multiple parameters to NodeJS callback using export module使用导出模块将多个参数传递给 NodeJS 回调
【发布时间】:2018-05-22 06:33:32
【问题描述】:

场景 1:

我的 atom 项目中有两个文件 weather.jsexmaple.js,weather 正在使用 export 模块将所有内容导出到 example.js,而 example.js 正在使用 require 模块

我的天气.js

var request = require('request');
module.exports= function(justAnothercallback) 
{
    justAnothercallback('This is from weather');
}

myExample.js

var fromWeather = require('./weather.js');
fromWeather(function(weather){
    console.log(weather); 
});

如果我做节点myExample.js,输出是: 这是天气原因

场景 2: 现在我在weather.js 中再传递一个回调

module.exports= function(justAnothercallback, SecondCallback) {
    justAnothercallback('This is from weather');
    SecondCallback('This is second callback)');
}

并且我的example.js被修改以适应第二个回调函数!!

var fromWeather = require('./weather.js');
fromWeather(function(weather, anotherfunc){
    console.log(weather);
    console.log(anotherfunc);
});

从终端我们得到:

/>节点示例-callback.js 这是来自天气 未定义 /Users/NodeCourse/async/weather.js:7 SecondCallback('这是第二个回调)'); ^

TypeError: SecondCallback 不是函数 在 module.exports (/Users/oogway/NodeCourse/async/weath

我的问题是它们不一样,我只是添加了一个回调,它被吐了!为什么 !!??但如果我只通过一个回调它就可以正常工作.. 请帮忙。

【问题讨论】:

    标签: javascript node.js module callback


    【解决方案1】:

    在您的代码中,您只传递带有 两个 参数的 一个 回调

    var fromWeather = require('./weather.js');
      fromWeather(function(weather, anotherfunc){
        console.log(weather);
        console.log(anotherfunc);
      });
    

    这就是两个回调的样子

    var fromWeather = require('./weather.js');
      fromWeather(function(){
        console.log('Hello from callback 1');
      }, function(){
        console.log('Hello from callback 2');
      });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-01
      • 2014-04-20
      • 2020-08-15
      • 2016-12-13
      • 2016-12-09
      相关资源
      最近更新 更多