2017-03-02 28 views
0

在棱角分明,有打电话给$ http服务和附加回调的成功和错误的选项:JavaScript的节点追加多个调用的函数

$http.get(url).success (function() { do A}).error (function() { do B}); 

我想实现它在JavaScript上的节点,所以我创建新的文件,并写入了ollowing代码

file1.js:

module.exports = 
{ 


    get: function (url) { 
     //should be sync implementation 
     console.log("get function"); 
    }, 

    error: function (url) { 

     console.log("error function"); 
    }, 

    success: function (url) { 

     console.log("success function"); 
    } 
} 

而从文件2:

var global = require('./file1'); 
file1.get("some string") 
    .success(function() { console.log("success") }) 
    .error(function() { console.log("success") }) 

然后,我从咕噜与jasmine_nodejs插件运行。 但这不起作用。如何定义可以附加功能的模块?

回答

0

功能必须与其他的功能,你可以再返回链的对象。例如。如果您的get函数返回{ foo: function() { ... } },那么您可以按如下方式链接它:get().foo()

角用途promises HTTP请求,因为这些都是异步操作。

0

$http服务正在执行异步操作,并且该语法基于名为Promises的概念。

让我们来看看你的榜样,并把它变成基于无极模块。现在

module.exports = { 
    get: function(url) { 
     return new Promise(function(resolve, reject) { 
      // Perform your operation here. 
      // ... 
      // After your operation, depending on the status of your object, 
      // you want to call either resolve or reject. 
      setTimeout(function() { 
       resolve("Success!"); 
       // or you can call reject("Fail!"); 
      }, 250); 
     }) 
    } 
} 

,你应该能够做到这一点:

var file1 = require('./file1'); 
file.get("some string") 
    .then(function() { console.log("success") }) 
    .catch(function() { console.log("error!") }) 

请记住,当你调用resolve(...)功能,它会触发.then方法与参数。反之亦然,当你拨打reject(...)它会触发.catch功能。

+0

我想实现的场景相当于角HTTP服务。我的意思是我想自己定义2个或更多函数,并传递一个回调来处理从第一个get函数得到的结果(例如,从http服务器获取信息或其他函数),并且可以将其他函数附加到此函数中,例如:get.func1(回调).func2(回调)。 func1/2/3 ...可以是我可以根据第一个函数的结果自行决定的任何场景。谢谢 – Moti

0

让每个函数返回此:

module.exports = { 
    get: function (url) { 
     //should be sync implementation 
     console.log("get function"); 
     return this; 
    }, 
    error: function (url) { 
     console.log("error function"); 
     return this; 
    }, 
    success: function (url) { 
     console.log("success function"); 
     return this; 
    } 
} 

这将让您链。但我强烈建议你使用框架来做到这一点。

+0

我不认为这会起作用,在这个模块范围内的this'取决于调用者的有界函数。 – tpae

+0

如果我将这些功能连接在一起,它就无法工作... – Moti