简体   繁体   English

我可以在JavaScript中强制解决承诺以等待结果吗?

[英]Can I force the resolution of a promise to await results in javascript?

This question is somewhat academic in that I don't have a real need to do this. 这个问题有点学术性,因为我并不要这样做。

I'm wondering if I can force the resolution of a promise into a returned value from a function such that the function callers are not aware that the functions contain promised async operations. 我想知道是否可以强制将promise解析为函数的返回值,以使函数调用者不知道该函数包含promise异步操作。

In .NET I can do things like this by using functions on Task[] or return Task.Result which causes the caller to await the completion of the task and callers won't know or care that the work has been done using tasks. 在.NET中,我可以通过使用Task[]上的函数或return Task.Result来执行类似的操作,这将导致调用方等待任务的完成,并且调用方将不知道或不在乎使用任务已完成了工作。

If you're using ES6 you can use a generator to make code like this. 如果您使用的是ES6,则可以使用生成器来生成类似这样的代码。 It essentially comes close to 'blocking' on the promise, so you have the appearance of a long-running method that just returns the value you want, but async/promises live under the covers. 它实质上接近于对诺言的“阻塞”,因此您会看到一个长期运行的方法,该方法只返回您想要的值,但异步/承诺却在幕后。

let asyncTask = () =>
  new Promise(resolve => {
    let delay = Math.floor(Math.random() * 100);

    setTimeout(function () {
      resolve(delay);
    }, delay);
  });

let makeMeLookSync = fn => {
  let iterator = fn();
  let loop = result => {
    !result.done && result.value.then(res =>
      loop(iterator.next(res)));
  };

  loop(iterator.next());
};

makeMeLookSync(function* () {
  let result = yield asyncTask();

  console.log(result);
});

More explanation and the source available here: http://www.tivix.com/blog/making-promises-in-a-synchronous-manner/ 有关更多说明和信息源,请参见: http : //www.tivix.com/blog/making-promises-in-a-synchronous-manner/

Here is the code compiled on Babeljs.io 这是在Babeljs.io上编译的代码

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM