簡體   English   中英

如何使用angular2和typescript鏈接3個Promises

[英]How to chain 3 Promises with angular2 and typescript

我已經成功地將承諾鏈接起來,但我發現我的方式足夠復雜:我想知道是否有更優雅的方式來做到這一點。

我使用Angular2,Typescript和signalR。

我有一個服務getIntervention ,它通過Id從服務器返回一個對象。

在調用getIntervention之前,我想檢查客戶端是否連接到服務器,在連接到服務器之前,我想要加載SignalR腳本。

所以我創建了第一個promise scriptLoadedPromise ,它等待加載SignalR腳本。 解析scriptLoadedPromise ,會創建一個等待建立連接的新promise connectionPromise

解決connectionPromise ,請調用服務getIntervention

對於每個promise,我添加了名為scriptLoadedconnectionDetected回調調用resolve()

這是我的代碼:

public loadIntervention( numFI : number ) : Promise<Intervention>
{

    let scriptLoadedPromise : Promise<Intervention> = new Promise( ( resolve, reject ) =>
    { 
        // si le script est chargé alors la promesse est déjà tenue
        if ( this.isScriptLoaded )
            resolve();
        else
            this.scriptLoaded = ( () => { resolve(); } ) ;
    }).then
    ( () => {
        let connectionPromise : Promise<Intervention> = new Promise( (resolve, reject) =>
        {
            // si le serveur est connecté alors la promesse de connection est déjà tenue
            if ( this.Connected )
                resolve();
            else
                this.connectionDetected = ( () => { console.log("RECONNETED !!!!!"); resolve(); } );

        } )
        .then( ()  => { return this.proxy.server.getIntervention( numFI ); } );

        return connectionPromise;
    });


    return scriptLoadedPromise;
}

有沒有辦法簡化3個承諾鏈接的實現?

如果這些承諾相互依賴,那么它與您已經創建的相似。 您可以通過將邏輯放入單獨的方法(如例如)來增強代碼風格

private firstAction():Promise<any> {
  return new Promise<any>(
    (resolve, reject) => { ... }
  );
}
private secondAction():Promise<any> {
  return new Promise<any>(
    (resolve, reject) => { ... }
  );
}
execute() {
  this.firstAction().then(
    (firstResult:any) => this.secondAction().then(
      (secondResult:any) => { ... }
    );
  )
}

如果允許並行執行promise,則可以使用Promise.all() ,例如

execute() {
  let promises:Promise<any>[] = [];
  promises.push(this.firstAction());
  promises.push(this.secondAction());

  Promise.all(promises).then(
    () => { ... }
  );
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM