【问题标题】:Turning my function into an async function将我的函数变成异步函数
【发布时间】:2017-10-12 19:11:24
【问题描述】:

在我的 Angular 应用程序中,我有一个方法,我需要推迟它的执行,直到后端的值可用:这是方法:

redrawGrid(params: any): void {
    params.node.childFlower.setRowHeight( (this.globalRowCount * 34 ) + 34) ;
    this.gridOptions.api.onRowHeightChanged();
}

我需要这个方法在 this.globalRowCount(作为从服务返回的全局值)从后端返回之后执行。

变量 this.globalRowCount 来自对 observable 的订阅

this.userlistService.childRowLength.subscribe( (num: number) => {
    this.globalRowCount = num;
    console.log(this.globalRowCount + ' globalRowCount after num assigned');
});

我读到我可以使这个函数异步并使用等待......?我该怎么做?

【问题讨论】:

  • 你试过什么?你看过承诺吗?
  • 需要对实际调用redrawGrid的代码进行更改。代码只应在 this.globalRowCount 更新后调用 redrawGrid。实际上,您根本不必更改 redrawGrid(至少据我所知,鉴于您提供的信息)。
  • 异步等待需要发生在获得 globalrowCount 的函数中,而不是在使用它的函数中。

标签: javascript angular typescript asynchronous


【解决方案1】:

这就是您可以返回 Promise 的方式,这就是这些天所有酷孩子在 JavaScript 和 TypeScript 中执行异步的方式。

function redrawGrid(params: any): PromiseLike<void> {
    return new Promise((resolve, reject) => {
        params.node.childFlower.setRowHeight((rowCount * 34) + 34);
        this.gridOptions.api.onRowHeightChanged();
        resolve();
    });
}

您还可以处理错误并在出现问题时拨打reject,让您的消费者处理任何问题。

这不会在这段代码执行时改变,所以如果你想在其他异步操作之后调用它,你真的希望在其他异步操作解决后调用它。 .. 我不知道您使用的 API,但我们正在谈论类似以下伪代码的内容...

redrawGrid(params: any): void {
    // the getGlobalRowCount is now the method returning a promise
    this.getGlobalRowCount()
        .then((rowCount) => {
            params.node.childFlower.setRowHeight((this.globalRowCount * 34) + 34);
            this.gridOptions.api.onRowHeightChanged();
            resolve();
    });
}

【讨论】:

  • 其实很酷的孩子使用 observables 或 async await 但我还是喜欢 promises
  • @rjustin 接受挑战。我尊重这一点。
  • 我会投票赞成在 Angular2 中使用 Observables。即developer.telerik.com/topics/web-development/…
  • 我想我理解了大意,但我不等待另一个异步操作完成。该变量来自对 observable 的订阅。我已经更新了我的问题。
【解决方案2】:

您可能对在哪里使用 async await 感到困惑,但您可能想要这样的东西:

async redrawParentFunction(){
    if(!this.globalRowCount)
        this.globalRowCount = await http.get(....).toPromise()//some promise
    this.redrawGrid(....)
}

redrawGrid(params: any): void {

        params.node.childFlower.setRowHeight( (this.globalRowCount * 34 ) + 34) ;
        this.gridOptions.api.onRowHeightChanged();

}

Async 放在必需的函数名前面。

await 在 promise 之前而不是 then()。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-16
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多