![](/img/trans.png)
[英]How to properly apply Function.apply.bind to Promise's resolution handler then()?
[英]How does function.apply.bind work in the following code?
因此,我从promise中返回了一个[200,599]的数组,并且传播中的回调函数被传递到Function.apply.bind中,但是现在我迷失了。 [200,599]的数组如何拆分为x和y? apply.bind是如何工作的?
function getY(x) {
return new Promise( function(resolve,reject){
setTimeout( function(){
resolve( (3 * x) - 1 );
}, 100 );
} );
}
function foo(bar,baz) {
var x = bar * baz;
// return both promises
return [
Promise.resolve( x ),
getY( x )
];
}
function spread(fn) {
return Function.apply.bind( fn, null );
}
Promise.all(
foo( 10, 20 )
)
.then(
spread( function(x,y){
console.log( x, y ); // 200 599
} )
)
.apply()
是函数对象上的一种方法。 像这样:
console.log(Math.max.apply(null, [1, 2, 3])); // 3
.apply()
接受两个参数,上下文(什么将成为this
目标函数内)和一个可迭代的参数(通常是一个数组,但arguments
数组一样也适用)。
.bind()
是函数对象的一种方法。 像这样:
const x = { foo: function() { console.log(this.x); }, x: 42 } var myFoo = x.foo.bind({x: 5}); x.foo(); // 42 myFoo(); // 5
.bind()
获取一个上下文(将会变成this
),以及可选的其他参数,并返回一个新的函数 ,其中上下文已绑定 ,并且其他参数已锁定
由于.apply()
本身就是一个函数,因此可以将其与.bind()
绑定,如下所示:
Function.prototype.apply.bind(fn, null);
这意味着this
的.apply()
是fn
和第一个参数.apply()
将null
。 意思是这样的:
fn.apply(null, args)
它将散布数组中的参数。
Spread接受一个函数,并将apply
方法 绑定到其中,部分应用null
参数。 简而言之,
spread(fn)
转化为
args => fn.apply(null, args)
与使用ES6扩展语法相同
args => fn(...args)
该函数的名称来源于何处。
如果您想得到长答案,请记住bind
作用:
method.bind(context, ...args1)
返回一个像
(...args2) => method.call(context, ...args1, ...args2)
在我们的例子中, method
为apply
, context
为fn
,第一个参数为null
,因此调用
Function.apply.bind( fn, null )
将创建一个功能类似于
(...args2) => (Function.apply).call(fn, null, ...args2)
考虑到apply
是两次访问均从Function.prototype
继承的方法,因此它等效于上面的fn.apply(…)
调用。
传播函数只是将数组转换为传递给函数的参数的实用函数。 apply正在执行转换,并且bind将其绑定到调用函数,以便“ this”上下文连接到同一函数。
以简单的形式查看传播方式->
spread(function (x,y){console.log(x,y);})([1,2])
您将得到答案1 2,因为1传递给x,2传递给y。
因此,在您的示例中,您的promise.all返回一个已解决的promise数组。 然后将它们映射到函数(x,y)的参数。
它的工作原理的原因是的“解构”性质apply
(如果给定的值的阵列,它们将提供蔓延到你使用应用上的功能)。
现在回到您的代码,当在apply上调用bind时,返回的值是一个函数,该函数返回提供给bind
的相同函数,唯一不同的是执行时将使用apply
调用(在您的情况下为thisArg数组),但直到您调用它,它才会执行。 在您的诺言已解决的情况下,将使用Promise
解析提供的参数数组执行then
提供的功能。
function spread(fn){ let boundedFn = fn.bind(fn) return function(arg){ return boundedFn.apply(null,arg) } } spread((x, y, c) => console.log(x, y, c))([1,2,3]) // or Promise.resolve([6, 5]).then(spread((a, b) => console.log(a, b)))
其原因bind
提供(在代码中)与null
作为第二参数是防止由呼叫者从报错提供的阵列apply
作为其第一个参数,其保留用于this
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.