簡體   English   中英

承諾要進行ES6重組?

[英]Promises with ES6 destructuring?

我嘗試將Promises與ES6解構語法混合(僅出於實驗目的),但是以下代碼引發錯誤:

function delay(ms) {
  return new Promise((resolve, reject) => {
    setTimeout(() => resolve(), ms)
  })
}

const { then } = delay(2000)

console.log(typeof then) // ==> 'function'

// throws TypeError:
then(() => {
  console.log(`done!`)
})

在Node.js v7.10.1上打印:

TypeError:無法讀取未定義的屬性'Symbol(promise_state_symbol)'

Chrome控制台還會引發TypeError ,但消息不同:

Uncaught TypeError:方法Promise.prototype.then在不兼容的接收器上調用undefined

這些錯誤對我說的並不多。 有什么更好的解釋呢?

這意味着, then是方法,你沒有把它在任何情況下-你說這就是因為沒有任何一個功能this方面 (或“接收器”,作為第二個錯誤消息,將其命名為正常)。 您基本上是

const then = Promise.prototype.then
console.log(typeof then) // ==> 'function'
then(() => {}) // throws TypeError

您可以使用call

const promise = delay(2000);
then.call(promise, console.log);

或者只是正確調用promise.then(console.log)

您正在將then方法分配給變量, then訪問this 您可以使用bind實現您想要的。

基本上,javascript中的方法只是使用this函數。 如果您在“竊取”該功能並且不提供該值,那么您將處於危險境地。

另外, then你提取是最有可能從Promise.prototype ,不特定的延時功能的函數。

您剛剛找到了從對象中獲取方法的絕佳方法。 完全與解構無關...

let p;
const {then} = p = delay(2000);
const then1 = p.then;

console.assert(then === Promise.prototype.then)
console.assert(then1 === then, 'thens aren\'t the same')

但是你想then ,以某種方式確保,那你怎么稱呼它右邊的承諾。

所以你可以選擇

const p = delay(2000);
const then = p.then.bind(p);
…

或構造另一個匿名函數

const p = delay(2000);
const then = fn => p.then(fn)

請注意,這不是您想要的,因為它在您調用then時開始超時。

const then = fn => delay(2000).then(fn) // ⚠ setTimeout gets called when you are calling then.

我看不到您如何在一線達成目標,但是其他人可能有一個主意。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM