javascript - Creating a (ES6) promise without starting to resolve it -


using es6 promises, how create promise without defining logic resolving it? here's basic example (some typescript):

var promises = {}; function waitfor(key: string): promise<any> {   if (key in promises) {     return promises[key];   }   var promise = new promise(resolve => {     // don't want try resolving here :(   });    promises[key] = promise;   return promise; }  function resolvewith(key: string, value: any): void {   promises[key].resolve(value); // not valid :( } 

it's done other promise libraries. jquery's example:

var deferreds = {}; function waitfor(key: string): promise<any> {   if (key in promises) {     return deferreds[key].promise();   }   var def = $.deferred();       deferreds[key] = def;   return def.promise(); }  function resolvewith(key: string, value: any): void {   deferreds[key].resolve(value); } 

the way can see store resolve function away somewhere within promise's executor seems messy, , i'm not sure it's defined when function run - run on construction?

thanks.

good question!

the resolver passed promise constructor intentionally runs synchronous in order support use case:

var deferreds = []; var p = new promise(function(resolve, reject){     deferreds.push({resolve: resolve, reject: reject}); }); 

then, @ later point in time:

 deferreds[0].resolve("hello"); // resolve promise "hello" 

the reason promise constructor given that:

  • typically (but not always) resolution logic bound creation.
  • the promise constructor throw safe , converts exceptions rejections.

sometimes doesn't fit , resolver runs synchronously. here related reading on topic.


Comments

Popular posts from this blog

python - No exponential form of the z-axis in matplotlib-3D-plots -

php - Best Light server (Linux + Web server + Database) for Raspberry Pi -

c# - "Newtonsoft.Json.JsonSerializationException unable to find constructor to use for types" error when deserializing class -