Creating a (ES6) promise without starting to resolve it

后端 未结 6 518
甜味超标
甜味超标 2020-12-07 17:15

Using ES6 promises, how do I create a promise without defining the logic for resolving it? Here\'s a basic example (some TypeScript):



        
6条回答
  •  悲哀的现实
    2020-12-07 17:55

    Things are slowly getting better in JavaScript land, but this is one case where things are still unnecessarily complicated. Here's a simple helper to expose the resolve and reject functions:

    Promise.unwrapped = () => {
      let resolve, reject, promise = new Promise((_resolve, _reject) => {
        resolve = _resolve, reject = _reject
      })
      promise.resolve = resolve, promise.reject = reject
      return promise
    }
    
    // a contrived example
    
    let p = Promise.unwrapped()
    p.then(v => alert(v))
    p.resolve('test')
    

    Apparently there used to be a Promise.defer helper, but even that insisted on the deferred object being separate from the promise itself...

提交回复
热议问题