Chr*_*ens 28 javascript asynchronous promise deferred
我显然误解了js promises的解决方式或者"return"的语义.
我被一个期望我同步的函数调用 - 返回一个值.计算该值需要一些异步代码(特别是dstore Collection上的ForEach方法)
我想要完成的是大约这个,但这不起作用mySynchronousFunction函数没有返回值.
function mySynchronousFunction() {
var accumulator = {};
var myPromise = doAsynchronousThingThatSideEffectsAccumulator();
// Now my caller is expecting the value of accumulator.
myPromise.then(function() {return accumulator;})
}
Run Code Online (Sandbox Code Playgroud)
我知道JS必须允许单线程实现,因此阻止它并不酷,但必须有一些模式来粘合异步到同步代码,我刚刚错过了.
jfr*_*d00 22
您无法在Javascript中通过异步操作生成同步结果.你不能这样做.如果操作的任何部分是异步的,则整个结果必须是异步的,并且您必须使用回调,承诺或其他此类机制来在操作完成且结果准备就绪时进行通信.
如果您的异步操作已经返回一个promise(它看起来像),那么您应该从包装器函数返回它:
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
});
Run Code Online (Sandbox Code Playgroud)
您可能还需要注意,通过副作用运行的函数很少是最佳设计模式.您也可以传入输入并让它通过已解决的承诺返回输出并完全避免副作用.
Guf*_*ffa 10
不,没有办法让异步代码同步.一旦进行了异步调用,就必须一直异步处理结果.
JavaScript是单线程的,因此如果你创建一个等待结果的阻塞循环,那么处理结果的代码就没有机会运行.
如果要从异步函数返回某些内容,则必须返回一个承诺,调用代码可以使用该承诺异步处理结果.
| 归档时间: |
|
| 查看次数: |
33010 次 |
| 最近记录: |