[英]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.