等待BaconJS中依赖ajax流的最新值?
问题描述:
我有3条流。 (1)gradingResult
和contextId
是依赖于studentResponse
的ajax请求。 (2)对于每个studentResponse
值,我需要使用studentResponse
值和其他两个流的相应结果来触发事件。等待BaconJS中依赖ajax流的最新值?
此问题与Wait for latest values from dependent streams in BaconJS?相似但不同。一个关键的区别是,我不知道gradingResult
和contextId
哪个会先返回。
关于代码的说明:代码基于生产代码。我无权访问gradingResult
或contextId
。我所知道的是,他们是从studentResponse
获取输入的ajax请求。
与期望的输出的一些示例代码:
function _fauxAjax(val) {
return Bacon.fromBinder(function(sink) {
setTimeout(function() {
sink(val);
sink(new Bacon.End());
}, Math.random()*1000);
return function() {}
});
}
var studentResponse = new Bacon.Bus();
var gradingResult = studentResponse.flatMap(_fauxAjax);
var contextId = studentResponse.flatMap(_fauxAjax);
鉴于这种输入:
studentResponse.push(1);
studentResponse.push(2);
studentResponse.push(3);
希望的输出:
{studentResponse:1, gradingResult:1, contextId:1 }
{studentResponse:2, gradingResult:2, contextId:2 }
{studentResponse:3, gradingResult:3, contextId:3 }
答
如果定义两个后者AJAX请求作为独立流,我没有看到确保这些值相关的实际解决方案。
因此,要绝对确保你得到的是由同studentResponse
触发gradingResult
和contextId
回复我说你必须做这样的事情:
studentResponse.flatMap(function(response) {
return Bacon.combineTemplate({
studentResponse: response,
gradingResult: _fauxAjax(response),
contextId: _fauxAjax(response)
})
}).log()