函数递归和承诺

问题描述 投票:0回答:2

我有一个函数谁发送异步请求的文件块(tmp是我的块)

uploadChunk: function (uploadId, content, offset) {
  var tmp = content.slice(offset, offset + constants.ChunkSize);
  restRequest({
    method: 'POST',
    url: 'file/chunk?uploadId=' + uploadId + '&offset=' + offset,
    data: tmp,
    processData: false,
    contentType: false
  }).then(function (resp) {
    // When the upload is finished, we have an json object with a field '_modelType'
    if (typeof resp._modelType === "undefined" || resp._modelType == null) {
       return this.uploadChunk(uploadId, content, resp.received);
    }
    // Here, file is fully upload
  }.bind(this));
}

我想只在我的文件完全上传并使用时才返回一个承诺:

this.uploadChunk(uploadId, content, 0).then(function (){
  console.log("My file is uploaded");
  .... // use my new file
})

我试图创建一个promise但是一旦我的函数被递归调用,就不再定义resolve函数了。

需要帮忙 :)

javascript ajax recursion promise
2个回答
1
投票

我想只在我的文件完全上传并使用时才返回一个承诺:

你提出的建议没有任何逻辑意义。承诺的整个要点(以及一般的异步代码)是它们没有立即完成。因此,即使您稍后可以返回某些内容,您的函数的原始调用者也会很久没有收到您返回的值。

幸运的是,你已经有98%的方法来解决这个问题而且没有意识到这一点。

你只需要在这里添加return这个词

return restRequest({

当有更多工作要做时,你的.then()方法的uploadChunk部分会返回一个承诺。这意味着您最初从uploadChunk函数返回的承诺将继续等待,直到完成所有工作。

就试一试吧。


-1
投票

如何使用回调代替承诺通知已完成的操作

uploadChunk: function (uploadId, content, offset, callback) {
  var tmp = content.slice(offset, offset + constants.ChunkSize);
  restRequest({
    method: 'POST',
    url: 'file/chunk?uploadId=' + uploadId + '&offset=' + offset,
    data: tmp,
    processData: false,
    contentType: false
  }).then(function (resp) {
    // When the upload is finished, we have an json object with a field '_modelType'
    if (typeof resp._modelType === "undefined" || resp._modelType == null) {
       return this.uploadChunk(uploadId, content, resp.received, callback);
    }
    // Here, file is fully upload
    callback && callback(resp);
  }.bind(this));
}

然后对此回调中的操作事件做出反应

this.uploadChunk(uploadId, content, 0, function(resp) {
  console.log("My file is uploaded");
  .... // use my new file
});

因此,即使您有递归,每次操作完成时您都会收到通知。

© www.soinside.com 2019 - 2024. All rights reserved.