2

I'm looking at both PromiseJS and ES6 for something similar to a CompletableFuture, but couldn't find any.

Any suggestions how this can be achieved in javascript? Thanks

Note: Promise.resolve() isn't suitable, unless you can create the Promise object first and complete it later.

Update

As all answers pointed out, the correct way is to use Promise's constructor:

new Promise((resolve, reject) => { resolve(data); })
Michel Jung
  • 2,966
  • 6
  • 31
  • 51
stackoverflower
  • 3,885
  • 10
  • 47
  • 71
  • 1
    Yes, it is possible to create `Promise` object, then resolve at future point. Can you include `javascript` tried at Question? Describe expected result? – guest271314 Jun 24 '16 at 13:53
  • Please show us the code that you would like to write and we can tell you how to do it correctly. As it stands, it really isn't a very specific question. – Bergi Jun 24 '16 at 14:44
  • Here's how you make a deferred object using ES6 standard promises (if that's what you're trying to do): http://stackoverflow.com/questions/37651780/why-does-the-promise-constructor-need-an-executor/37673534#37673534 – jfriend00 Jun 24 '16 at 15:03

3 Answers3

4

Note: Promise.resolve() isn't suitable, unless you can create the Promise object first and complete it later.

You can use Promise constructor, pass onFulfilled, onRejected arguments outside scope of executor function

var complete, err, now = new Date().getTime();

var promise = new Promise((onFulfilled, onRejected) => {
  complete = onFulfilled; err = onRejected;
});

promise.then((data) => {
  console.log(data)
});

setTimeout(() => {
  complete("promise resolved " 
           + (new Date().getTime() - now) 
           + " in the future")
}, Math.random() * 3500)
guest271314
  • 1
  • 15
  • 104
  • 177
0

There is no deferred-like API in JavaScript for good reason. You don't have a CompletableFuture with a .complete method, instead you just use the new Promise constructor. You already linked some documentation containing examples so I'm not going to repeat them here.

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
0

Just meet the same need, this is how I do this in TypeScript

export function createLazyPromise<T = any>(): Promise<T> & { reject: () => void, resolve: (v: T) => void } {
  let onResolve, onReject;
  const promise = new Promise<T>(((resolve, reject) => {
    onResolve = resolve;
    onReject = reject
  }));
  promise['resolve'] = onResolve;
  promise['reject'] = onReject;
  return promise as any
}

Usee like this

test('test shell', async () => {
  // resolve later
  const promise = createLazyPromise();
  const result = shell.exec(
    'ps aux | head -3',
    {
      silent: true,
    },
    (code, stdout, stderr) => {
      promise.resolve({code, stdout, stderr});
    }
  );

  console.log(result.pid);

  console.log(await promise);
});
wener
  • 7,191
  • 6
  • 54
  • 78