2017-04-03 10 views
0

サーバが要求の適切なステータスを返すまで、私は約束を数回発射したかったのです。私はこの関数を 'checkStatus'と呼んだ。私はこれをどのように達成するか考えていません。約束チェーンの再帰関数

saveFile() { 
    this.createMetadataContainer(this.fileId).then((data) => { 
    this.metadataInfo = data; 
    return this.createResourceMember(data, this.fileId, this.code); 
    }).then((data) => { 
    this.metadataInfo = data; 
    return this.applyCodeChanges(data); 
    }).then((data) => { 
    return this.checkStatus(data.id, this.metadataInfo); 
    }).catch((err) => { 
    this.deleteMetadataContainer(this.metadataInfo); 
    }).then((data) => { 
    this.msg = 'Code Saved'; 
    }); 

} 

そして、これは私がのcheckStatus機能を書いた方法です:

checkStatus(id, metadataInfo) { 
    let promise = this.server.retrieve('ContainerAsyncRequest', id).then((data) => { 
    if(data.State == "Completed") { 
     return data; 
    }else if(data.State == "Queued") { 
     this.msg = 'Saving Code...'; 
     return setTimeout(this.checkStatus(id, metadataInfo), 2000); 
    }else { 
     this.msg = 'Compiler Error ' + data.CompilerErrors; 
     return data; 
    } 
    }); 
    return promise; 
} 

答えて

0

setTimeoutは約束し、コールバックが無視されるようにあなたが渡された「再帰呼び出し」の結果を返しません。

function wait(t) { 
    return new Promise(resolve => { 
     setTimeout(resolve, t); 
    }); 
} 

を、チェーンでそれを使用します:だからタイムアウトをpromisify

checkStatus(id, metadataInfo) { 
    return this.server.retrieve('ContainerAsyncRequest', id).then(data => { 
    if (data.State == "Completed") { 
     return data; 
    } else if (data.State == "Queued") { 
     this.msg = 'Saving Code...'; 
     return wait(2000).then(() => 
     this.checkStatus(id, metadataInfo) 
    ); 
    } else { 
     this.msg = 'Compiler Error ' + data.CompilerErrors; 
     return data; 
    } 
    }); 
} 
+0

おかげで、それが働いています。私は約束を学んでおり、あなたは私をたくさん助けます。 –

関連する問題