如何阻止javascript承诺并返回已解决的结果? [英] How to block for a javascript promise and return the resolved result?

查看:163
本文介绍了如何阻止javascript承诺并返回已解决的结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我显然误解了js promises的解决方式或者return的语义。

I am obviously misunderstanding something about either the way js promises are resolved or about the semantics of "return."

我被一个期望我的函数调用同步 - 返回一个值。计算该值需要一些异步代码(特别是上的ForEach方法) dstore Collection

I am being called by a function that expects me to be synchronous - to return a value. Calculating that value requires some asynchronous code (specifically, the ForEach method on a dstore Collection

我想要完成的是大约这个,但这不起作用,因为函数mySynchronousFunction没有返回值。

What I'm trying to accomplish is approximately this, but this does not work in that the function mySynchronousFunction has no return value.

function mySynchronousFunction() {
   var accumulator = {};
   var myPromise = doAsynchronousThingThatSideEffectsAccumulator();
   // Now my caller is expecting the value of accumulator.
   myPromise.then(function() {return accumulator;})
}

我知道JS必须允许单线程实现,因此阻塞它并不酷,但必须有一些模式用于将异步粘合到同步代码上,我只是错过了。

I understand that JS has to allow for single-threaded implementations, so that it's not cool to block, but there must be some pattern for gluing asynchronous to synchronous code, that I've just missed.

推荐答案

你无法从中获得同步结果Javascript中的异步操作。你不能这样做。如果操作的任何部分是异步的,则整个结果必须是异步的,并且您必须使用回调,承诺或其他此类机制在操作完成且结果准备就绪时进行通信。

You cannot make a synchronous result out of an asynchronous operation in Javascript. You just cannot do it. If any part of your operation is async, the entire result must be async and you must either use a callback, a promise or some other such mechanism to communicate when the operation is done and the result is ready.

如果您的异步操作已经返回一个promise(看起来像),那么您应该从包装函数返回它:

If your async operation already returns a promise (which it looks like), then you should just return that from the wrapper function:

function myWrapperFunction() {
   var accumulator = {};
   var myPromise = doAsynchronousThingThatSideEffectsAccumulator(accumulator);
   // Now my caller is expecting the value of accumulator.
   return myPromise.then(function(result) {
       // operate on the accumulator object using the async result
       return accumulator;
   })
}

myWrapperFunction.then(function(accumulator) {
   // write your code here that uses the accumulator result
});

您可能还需要注意,通过副作用运行的功能很少是最佳设计模式。您也可以传入输入并让它通过已解决的承诺返回输出并完全避免副作用。

You may also want to note that a function that operates via side effects is rarely the best design pattern. You may as well pass in the input and have it return the output via the resolved promise and avoid side effects entirely.

这篇关于如何阻止javascript承诺并返回已解决的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆