简体   繁体   中英

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.

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.

If you're using ES6 you can use a generator to make code like this. 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/

Here is the code compiled on Babeljs.io

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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