Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a (ES6) promise without starting to resolve it

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

var promises = {}; function waitFor(key: string): Promise<any> {   if (key in promises) {     return promises[key];   }   var promise = new Promise(resolve => {     // But I don't want to try resolving anything here :(   });    promises[key] = promise;   return promise; }  function resolveWith(key: string, value: any): void {   promises[key].resolve(value); // Not valid :( } 

It's easily done with other promise libraries. JQuery's for 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 only way I can see to do this would be to store the resolve function away somewhere within the promise's executor but that seems messy, and I'm not sure it's defined when exactly this function is run - is it always run immediately on construction?

Thanks.

like image 520
Barguast Avatar asked Jun 26 '15 09:06

Barguast


People also ask

How do you make a Promise without executing?

Without Executing If you find yourself wanting a "cold" promise in the sense that your promise doesn't execute until you await on it, you should just use an async function. Calling an async function returns a new promise every time.

What happens if you don't resolve a Promise?

A promise is just an object with properties in Javascript. There's no magic to it. So failing to resolve or reject a promise just fails to ever change the state from "pending" to anything else. This doesn't cause any fundamental problem in Javascript because a promise is just a regular Javascript object.

Does Promise all resolve?

The Promise. all() method takes an iterable of promises as an input, and returns a single Promise that resolves to an array of the results of the input promises.


1 Answers

Good question!

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

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

Then, at some later point in time:

 deferreds[0].resolve("Hello"); // resolve the promise with "Hello" 

The reason the promise constructor is given is that:

  • Typically (but not always) resolution logic is bound to the creation.
  • The promise constructor is throw safe and converts exceptions to rejections.

Sometimes it doesn't fit and for that it the resolver runs synchronously. Here is related reading on the topic.

like image 65
Benjamin Gruenbaum Avatar answered Sep 28 '22 14:09

Benjamin Gruenbaum