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

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

问题描述

我显然误解了 js 承诺的解析方式或返回"的语义.

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

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

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 中,您不能从异步操作中生成同步结果.你就是做不到.如果您的操作的任何部分是异步的,则整个结果必须是异步的,并且您必须使用回调、promise 或其他类似机制在操作完成且结果准备就绪时进行通信.

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.

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

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天全站免登陆