我一直在使用承諾在JavaScript中實現一些功能,但是對於一件事情感到困惑, w ^這兩個在承諾中比較b/w .then(doSomething())和.then(()=> doSomething())
Promise.resolve()
.then(doSomething())
和
.then(() => doSomething())
我一直在使用承諾在JavaScript中實現一些功能,但是對於一件事情感到困惑, w ^這兩個在承諾中比較b/w .then(doSomething())和.then(()=> doSomething())
Promise.resolve()
.then(doSomething())
和
.then(() => doSomething())
then
期望的功能。在第一種情況下,您傳遞給調用doSomething()
的結果then
,而在第二種情況下,您實際上正在傳遞一個調用doSomething()
的函數。
這些將是等效的(假設你不需要爭論或this
):
Promise.resolve().then(doSomething)
Promise.resolve().then(() => doSomething())
感謝盧卡斯,那就是我一直在尋找的 – Abhijeet
*「如果doSomething確實使用了這些,那將是等價的:」*這是不正確的。在'()=> doSomething()'中,'doSomething'內的this'將會是'undefined'(或全局對象)。 –
@Lucas圖案不嚴格等效 – guest271314
.then(doSomething())
的then
回調被調用之前立即調用doSomething
。
.then(() => doSomething())
創建一個新函數,它將成爲then
回調。
要在@Lucas答案,這是正確的,then
在允諾制定這樣(從MDN)擴大:
Promise.then(onFulfilled[, onRejected]);
Promise.then(function(value) {
// fulfillment
}, function(reason) {
// rejection
});
所以你的第一個參數是實現一個功能,你的第二個功能的拒絕論證,兩個論點都是函數,根據所發生的值傳遞值。
所以,@Lucas說,
Promise.resolve().then(() => doSomething())
實際上是調用你的函數,在剛剛傳入doSomething()
調用函數,如果沒有回報,這不會做任何事情,除非該函數返回返回一個值或未定義一個函數(這可能是一個不合理的方式去一個可靠的)。
在第一種情況下函數doSomething必須返回另一個函數,因爲.then()需要傳遞函數。 – Artur
你有什麼特別的困惑? –