Javascript 可完成的未来?

Javascript completable future?

我正在查看两个 PromiseJS and ES6 for something similar to a CompletableFuture,但找不到。

有什么关于如何在 javascript 中实现的建议吗?谢谢

注意:Promise.resolve()不适合,除非您可以先创建Promise对象,然后再完成它。

更新

正如所有答案所指出的,正确的方法是使用Promise的构造函数:

new Promise((resolve, reject) => { resolve(data); })

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

您可以使用 Promise 构造函数,在 executor 函数

范围之外传递 onFulfilledonRejected 参数

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)

在 JavaScript . You don't have a CompletableFuture with a .complete method, instead you just use the new Promise constructor. You already linked some documentation 中没有类似延迟的 API 包含示例,所以我不打算在这里重复它们。

正好满足同样的需求,我在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
}

像这样使用

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);
});