-3

This question here - from 2014 - outlines various ways to do a deferred promise:

Resolve Javascript Promise outside function scope

There is this MDN documentation about Deferred object does say that there is Promise.defer() - but that it is obsolete.

Is there a standard way to do a deferred Promise in Javascript now? I'm otherwise likely to implement one of the Deffered objects in that original question.

dwjohnston
  • 11,163
  • 32
  • 99
  • 194
  • 2
    No standard way. Note that using deferreds this way is generally held to be an anti pattern. It is (like most anti patterns) sometimes necessary, but esoteric enough that it wasn't included in the native Promise implementation. – Jared Smith Feb 12 '19 at 02:51
  • Huh - @JaredSmith Can you dive into that more? – dwjohnston Feb 12 '19 at 03:14
  • While I don't necessarily think your question is strictly a dupe, [check this out](https://stackoverflow.com/questions/28764182/avoiding-the-deferred-anti-pattern?lq=1). In those scenarios you can't avoid it you can fake it by assigning the resolve callback to a var in an outer scope and then passing it to the event listener. Use with caution: deferreds are almost never necessary (which is why the native implementation doesn't expose them). – Jared Smith Feb 12 '19 at 03:30
  • 1
    Relevant posts [When would someone need to create a deferred](https://stackoverflow.com/questions/32853105/when-would-someone-need-to-create-a-deferred/32857145#32857145) and [Deferred object in ES](https://stackoverflow.com/questions/37651780/why-does-the-promise-constructor-need-an-executor/37673534#37673534). – jfriend00 Feb 12 '19 at 03:45

1 Answers1

3

Is there a standard way to do a deferred Promise in Javascript now? I'm otherwise likely to implement one of the Deffered objects in that original question.

No. There is no standard way of doing this in the current versions of Javascript. Apparently, those shepherding the Promise specification believe the actual need for it (cases where the Promise executor function simply won't work) is rare enough that they'd rather not add it to the standard. There may also be a belief that if they add it to the standard, too many people would use it for situations where it shouldn't be used (cases where using the promise executor would make for better code). Obviously, that's all someone's opinion, but those who work on those standards get to decide what opinion to go with.

As you appear to know there are some pretty simple work-arounds to just define your own. As I previously indicated in the comments, here are a couple of relevant posts on the subject, including code for work-arounds: When would someone need to create a deferred and Deferred object in ES6.

jfriend00
  • 683,504
  • 96
  • 985
  • 979