2017-04-03 109 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不會返回一個承諾,你通過一個回調函數會被忽略的「遞歸調用」的結果。所以promisify超時:

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

和使用,在鏈條:

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

謝謝,它的工作。我正在學習Promises,你們幫了我很多。 –