2017-02-10 71 views
1

我正在使用节点js插件: https://www.npmjs.com/package/promise-sequence,我正在尝试的是在调用管道时将参数传递给每个函数。将参数传递给Promise序列

var Nightmare = require('nightmare'); 
var pipeline = require('promise-sequence/lib/pipeline'); 

var commonFunctions = require('./websites/_common/commonFunctions') 

var nightmare = Nightmare({ 
    show: true, 
    fullscreen : true, 
    waitTimeout: 10000 
}); 

    var resultsPromise = pipeline([ 
    commonFunctions.accessURL(nightmare), 
    commonFunctions.loginToWebsite(nightmare), 
    ]) 
    .then(() => commonFunctions.success(nightmare)) 
    .catch((error) => console.log(error)); 

然而,当我试图传递参数,它给了我一个错误:

TypeError: tasks[0].apply is not a function 
at C:\sad\node_modules\promise-sequence\lib\pipeline.js:25:57 
at process._tickCallback (internal/process/next_tick.js:103:7) 
at Module.runMain (module.js:607:11) 
at run (bootstrap_node.js:418:7) 
at startup (bootstrap_node.js:139:9) 
at bootstrap_node.js:533:3 

如何将我的噩梦变量传递给每一个被用作管道参数?

回答

2

您可以结合这些功能:

var resultsPromise = pipeline([ 
    commonFunctions.accessURL.bind(null, nightmare), 
    commonFunctions.loginToWebsite.bind(null, nightmare), 
])... 

或者使用匿名函数:

var resultsPromise = pipeline([ 
    function() { return commonFunctions.accessURL(nightmare); }), 
    function() { return commonFunctions.loginToWebsite(nightmare); }), 
])... 

,你可以把它用箭头功能更短,如果你正在使用ES6:

var resultsPromise = pipeline([ 
() => commonFunctions.accessURL(nightmare), 
() => commonFunctions.loginToWebsite(nightmare), 
])... 

这里需要注意的是,管道需要传递给它的函数数组,这些方法,我们保持传递函数,但commonFunctions.accessURLcommonFunctions.loginToWebsite将被称为nightmare变量。

你的代码不工作的原因,或者你说直接调用它们的原因是,当你调用你的函数时,它们开始执行,并且他们返回承诺,但是管道不期望承诺,而是期望函数返回promise,所以它会在这些函数开始执行时调用它们。绑定基本上创建了预先加载了给定参数的新函数,这就是我们在匿名函数中所做的事情。

+0

谢谢,它的工作。 – Coder

+0

为什么它不直接工作?为什么需要匿名功能? – Coder

+0

@PHPLover请参阅我在答案中编辑的最后一部分。 –