2016-12-29 99 views
0

我google了一些绑定的解释,但仍然非常困惑。我用以下方式使用承诺绑定。它正在工作,但我不知道为什么。希望有人能解释并帮助我解决我遇到的一个小问题。下面是示例代码:节点绑定并承诺

var temp1 = function(){ 
    return new Promise(function(resolve, reject){ 
     resolve("hello"); 
    }); 
}; 

var temp2 = function(para1, para2){ 
    console.log("1:", para1); 
    console.log("2:", para2) 
    return new Promise(function(resolve, reject){ 
     resolve(para1+" "+para2); 
    }); 
}; 

temp1().then(temp2.bind(null,"world")).then(function(out){ 
    console.log(out); 
}); 

输出:

1:世界\ 2:你好\ 世界你好\

我使用 “绑定”,因为它可以使代码清理和更容易的错误处理,否则我必须使用以下内容:

temp1().then(function(out1){ 
    return temp2(out1, "world").then(function(out2){ 
     console.log(out2); 
    }); 
}); 

除了如何绑定工作,我有以下问题:

temp1().then(temp2.bind(null,/*the second param is a property of the output from temp1*/)).then(function(out){ 
    console.log(out); 
}); 

我知道我可以随时打破链或增加额外链,实现它: 例如

temp1().then(function(out1){ 
    return temp2(out1, (out1.length).to_String()).then(function(out2){ 
     console.log(out2); 
    }); 
}); 

但它会真棒不要打破链条。所以我的两个问题:1.如何绑定工作,2.如何保持链(也没有额外的链),而我仍然可以访问之前的输出的属性在下一个函数的参数然后。 谢谢!

回答

1

Function.prototype.bind()

的bind()方法创建一个新的功能,调用它时,具有其将此关键字设置为所提供的值,与任何提供前述参数的给定序列,当新功能被称为。

从技术上讲,temp2.bind(null,"world")将返回一个函数并通过null,"world"作为参数。然后,这些参数与temp1的结果合并,该索引为"hello",索引号为0。因此,传递给temp2的实际参数是"hello", "world"

保持环比你可以写:

temp1() 
    .then(function (out) { 
    return temp2(out,"world") 
    }) 
    .then(function(out){ 
    console.log(out); 
    }); 

这就是为什么人们创造的承诺,这样就可以很好地把它们连。你给出的例子的作品,但它类似于Callback Hell。

+0

因为根据定义的论点是'任何提供'之前,结果不是“你好”,“世界”,而是“世界“, “你好”。我仍然不明白为什么参数不是'null',但世界“,你好”。初始的null似乎在某处被吃掉。 –

0

bind()用于设置稍后调用的函数的适当上下文。我不认为你需要在这种情况下使用它。如果你正在使用es6你可以做一些像这样:

temp1() 
    .then(out1 => temp2(out1, out1.length.toString())) 
    .then(console.log) 
    .catch(console.log); 

它使用一个隐含的回报。这是有效的,因为temp2()也返回一个promsie,所以我们可以将它链接到下一个承诺解析器