Javascript 如何使用最新的承诺?

Javascript 如何使用最新的承诺?,javascript,rxjs,rxjs6,Javascript,Rxjs,Rxjs6,为什么不能将一个承诺转换为一个可观察的,然后与和最新from一起使用呢。我不清楚为什么这不能解决 of('') .pipe( withLatestFrom(from(myPromise)), map((res) => { console.log('does not resolve', res); }) ) .subscribe(); WithLatestFrom仅在其源可观测发射时发射,因为(“”)的of在源到WithLatestFrom之

为什么不能将一个
承诺
转换为一个
可观察的
,然后与
和最新from一起使用呢。我不清楚为什么这不能解决

of('')
  .pipe(
    withLatestFrom(from(myPromise)),
    map((res) => {
      console.log('does not resolve', res);
    })
  )
  .subscribe();

WithLatestFrom
仅在其源可观测发射时发射,因为(“”)的
of
在源到WithLatestFrom之前发射,所以您的
WithLatestFrom
永远不会触发

以下代码将不起作用:

of('1 + 1')
  .pipe(
    withLatestFrom(new Promise(x => x("== 2"))),
    map(([res1,res2]) => console.log(res1, res2))
  )
  .subscribe();
但这将:

of('1 + 1')
  .pipe(
    delay(100), // <= delay source execution
    withLatestFrom(new Promise(x => x("== 2"))),
    map(([res1,res2]) => console.log(res1, res2))
  )
  .subscribe();
('1+1')的

.烟斗(
延迟(100),//x(==2”),
map(([res1,res2])=>console.log(res1,res2))
)
.subscribe();

这是
的预期行为。源可观察对象在承诺解析之前同步完成(异步)
withLatestFrom
仅在两个可观测对象发射至少一次后发射,然后仅在源可观测对象发射时发射

在你的例子中,可观测的源在承诺解决之前是完整的

of('').pipe(
  delay(100),
  withLatestFrom(from(myPromise)),
  tap(res =>
    console.log('should resolve', res)
  )
).subscribe();
更新#1:无延迟的解决方案 如果两个源观测值发射一次并完成,那么
forkJoin
是最好的

forkJoin({
  addition: of(1 + 1),
  promise: from(myPromise)
}).pipe(
  map(({addition, promise}) => {return /* something */})
)
combinelateest
forkJoin
类似,但它更适用于持续发出值的长寿命流。它等待其内部流全部开始发射,然后发射其所有最新值

combineLatest(
  of(1 + 1),
  from(myPromise)
).pipe(
  map(([addition, promise]) => {return /* something */})
)
或者,如果您希望将
与latestfrom
一起使用,并且您对时间限制感到满意

from(myPromise).pipe(
  withLatestFrom(of(1+1)),
  map(([promise, addition]) => {return /* something */})
)

应该有效。

可以将
与最新from一起使用
与承诺一起使用。您需要制作一个可复制的演示,因为不可能给出这样的建议。@martin我提供了一个演示,我有一个承诺,我希望使用withLatestFrom在map函数中使用解析值,这样我就可以访问这两个值(源观测值和承诺值)。我不是舒尔,你在问什么?感谢水晶般清晰的示例=)有没有任何建议,我可以如何在映射函数中获得源可观测值和承诺值,而不使用丑陋的hack作为延迟。你可以使用
observeOn(asyncScheduler)强制(“”)
异步运行<代码> >考虑使用<代码> CuleLeTestEng/<代码>操作程序> @ MNeMeNew添加了一些如何在不使用<代码>延迟>代码的情况下执行此操作的示例。