【问题标题】:Dexie - ToArray() **Type 'Promise[]>' is not assignable to type '[]'.**Dexie - ToArray() **Type 'Promise[]>' 不可分配给 type '[]'。**
【发布时间】:2018-03-20 12:15:24
【问题描述】:

要求是从localdb返回两个简单的数组。

功能是:

public getCaricamentoVeloceConf(): Observable<any> {
    let res = new RespOrdiniGetsceltecaricamentoveloce();

    res.tipo = this._WebDBService.Configurazione_CV_Scelte.toArray();
    res.ordinamento = this._WebDBService.Configurazione_CV_Ordinamento.toArray();

    return Observable.of(res);
  }

错误信息我得到的是:

类型“Promise”不可分配给类型“Tipo[]”

我认为这是因为 ToArray() 函数返回了一个承诺。

其实我需要的是,用两个数组组成 res 对象,但我不知道如何组合两个 promise toArray() 方法

有什么解决办法吗?

【问题讨论】:

  • 代码不够清晰。它应该返回 observable 但返回 null。那么res 会发生什么?见stackoverflow.com/help/mcve
  • 对不起,应该返回res,我编辑代码

标签: angular typescript es6-promise dexie


【解决方案1】:

试试这个:

import 'rxjs/add/observable/fromPromise'; 
import { Observable } from "rxjs/Observable";

public getCaricamentoVeloceConf(): Observable<any> {   
    var res = new RespOrdiniGetsceltecaricamentoveloce();
    return Observable.fromPromise(
        this._WebDBService.Configurazione_CV_Scelte.toArray().then(tipo => {     
            res.tipo = tipo;
            return this._WebDBService.Configurazione_CV_Ordinamento.toArray();
        }).then(ordinamento => {
            res.ordinamento = ordinamento;
            return res;
        })
     );
  }

【讨论】:

  • 只需将 Promise 转换为 observable(查看更新的答案)
【解决方案2】:

IndexedDB 是asynchronous,因此返回值应该是对结果的承诺,而不是结果本身。

对于 TypeScript 和 ES2017,处理 Promise 的自然方式是 async..await。如果该方法应该与可观察对象一起使用,则应将承诺转换为可观察对象。由于 RxJS 提供了比 ES6 承诺的更广泛的控制流功能,因此尽早完成它是有意义的,例如forkJoinPromise.all 的工作方式类似,并接受 Promise 和完整的 observables 作为源:

  public getCaricamentoVeloceConf(): Observable<any> {
    return Observable.forkJoin(
      this._WebDBService.Configurazione_CV_Scelte.toArray(),
      this._WebDBService.Configurazione_CV_Ordinamento.toArray()
    )
    .map(([tipo, ordinamento]) => Object.assign(
      new RespOrdiniGetsceltecaricamentoveloce(),
      { tipo, ordinamento }
    ))
  }

【讨论】:

  • 也是一个很好的答案!
猜你喜欢
  • 2022-08-04
  • 2017-12-24
  • 2019-02-08
  • 2022-09-30
  • 1970-01-01
  • 1970-01-01
  • 2017-03-21
  • 2021-08-27
  • 1970-01-01
相关资源
最近更新 更多