【问题标题】:How to create a Promise with two callbacks to wait for?如何创建一个带有两个等待回调的 Promise?
【发布时间】:2017-01-25 16:38:19
【问题描述】:

我的目标是创建一种方法来加载返回承诺的对象。当我有回调时,我只需要调用从回调创建 Promise 的“toPromise”。但是现在我想在从服务器获取对象之前包括等待重新连接到服务器。

public loadIntervention( numFI : number ) : Promise<Intervention>
{
    if ( ! this.Connected )
    {
        // here is the callback that detects reconnection
        jQuery.connection.hub.reconnected( () => { ???? }  );
    }


    return this.proxy.server.getIntervention( numFI ).toPromise();
}

我应该如何实现它?

【问题讨论】:

  • 你通常可以通过以下方式链接promise:return promiseA.then(() =&gt; { return ... &lt;do async operation, returning promiseB&gt;... }),所以从方法返回的promise只有在promiseB被解析时才会被解析,promiseB只有在promiseA被解析时才会被解析会。

标签: angular typescript promise


【解决方案1】:

你可以创建一个默认的,已经解决的承诺:

let reconnectionPromise = Promise.resolve();

那么,如果需要重连,只需将重连操作返回的promise赋值给reconnectionPromise即可:

reconnectionPromise = jQuery.connection.hub.reconnected( () => { ???? }  );

然后,在loadIntervention 函数的return 语句中,将两个promise 链接在一起:

return reconnectionPromise.then(() => this.proxy.server.getIntervention( numFI ).toPromise());

所以,在这种情况下,如果this.ConnectedtruereconnectionPromise 是一个已经解决的承诺,并且then 函数会立即被调用来执行this.proxy.server.getIntervention。否则,如果this.Connectedfalse,则reconnectionPromise 将在重新连接完成时解析并然后调用执行this.proxy.server.getInterventionthen 函数。

这里是完整的例子:

public loadIntervention( numFI : number ) : Promise<Intervention>
{
    let reconnectionPromise = Promise.resolve(); // Default, already resolved, promise
    if ( ! this.Connected )
    {
        // If you need to perform reconnection, assign to "reconnectionPromise" 
        // the promise returned by "jQuery.connection.hub.reconnected"
        reconnectionPromise = jQuery.connection.hub.reconnected( () => { ???? }  );
    }


    // Always chain the reconnectionPromise then do "getIntervention"
    return reconnectionPromise.then(() => this.proxy.server.getIntervention( numFI ).toPromise());
}

【讨论】:

    猜你喜欢
    • 2017-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多