2017-04-03 148 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,你们帮了我很多。 –