【问题标题】:Trouble forming a promise chain无法形成承诺链
【发布时间】:2016-11-01 18:58:35
【问题描述】:

我有一个函数必须连接到数据库以获取上传令牌,然后上传文件,然后关闭流并将文件记录到数据库中。我无法将所有这些链接在一起。

var saveNewRequest = function (image_arr) {
    return $.ajax({
        url: 'http://' + AppVar.ServerUrlWithPort + '/restapi/MtReqNewRequest_SaveData',
        type: 'POST',
        data: JSON.stringify({
            'SessionId': AppVar.SessionId,
            'Name': $('#MtReqNewRequest_name').val(),
            'Desc': $('#MtReqNewRequest_desc').val(),
            'Obj': $('#MtReqNewRequest_obj').val(),
            'Priority': $('#MtReqNewRequest_priority2').val(),
            'Status': $('#MtReqNewRequest_status2').val(),
            'Type': $('#MtReqNewRequest_type2').val()
        }),
        dataType: 'json',
        contentType: "application/json",
        timeout: 10000
    }).done(function (response) {
        if (response.ResultCode === '0') {
            if (image_arr.length != 0) {
                //this is recursively called upload function which returns jQuery promise (this works as intended)
                // the promise resolves with RequestId which I need later on
                return uploadImages(image_arr, image_arr.length, 0, response.RequestId)
            } else {
               //I would like this to return just this RequestId
                Promise.resolve(response.RequestId)
            }
        } else {
            Promise.reject().promise();
        }
    }).fail(function (x, t, m) {
        if (t === "timeout") {
            reject("Timeout: " + t);
        } else {
            reject($.i18n('Error-RetrivingDataProblem'));
        }
    })
}

我在一个事件中称之为:

    MtReq.saveNewRequest(image_arr).then(function (output) {
        AppVar.nav.popPage().then(function () {
            Utility.hideModalWithProgressBar();
            if (!isNaN(output)) {
                setTimeout(500, AppVar.nav.pushPage("MtReqRequestPage.html", { animation: "slide", id: output }));
            }
        })
    }).catch(function (e) {
        Utility.hideModalWithProgressBar();
        ons.notification.alert(e);
    })

我需要将 RequestID 传递给AppVar.nav.pushPage,以打开我刚刚创建的页面。但是,我在saveNewRequest 中收到了第一个 Ajax 请求的完整响应。

这是 Cordova 应用程序,使用 OnsenUI 框架(但这与问题无关)。另外,我正在使用最新的 BluebirdJs 作为 Promise polyfill(据我所知,这应该使 JS 和 jQuery 的 Promise 兼容)。

感谢您的帮助!

【问题讨论】:

  • 注意,Promise.reject() 没有.promise() 方法。 reject() 未在 .fail() 中定义。
  • 谢谢。我还在学习 promise 是如何工作的。有时这很令人困惑。然而,这并不能真正解决问题。

标签: javascript jquery promise bluebird


【解决方案1】:

.then()替换.done().done() 返回由 $.ajax() 返回的相同 jQuery 承诺对象。 return Promise 或来自 .then() 的其他值。

var saveNewRequest = function (image_arr) {
    return $.ajax({
        url: 'http://' + AppVar.ServerUrlWithPort + '/restapi/MtReqNewRequest_SaveData',
        type: 'POST',
        data: JSON.stringify({
            'SessionId': AppVar.SessionId,
            'Name': $('#MtReqNewRequest_name').val(),
            'Desc': $('#MtReqNewRequest_desc').val(),
            'Obj': $('#MtReqNewRequest_obj').val(),
            'Priority': $('#MtReqNewRequest_priority2').val(),
            'Status': $('#MtReqNewRequest_status2').val(),
            'Type': $('#MtReqNewRequest_type2').val()
        }),
        dataType: 'json',
        contentType: "application/json",
        timeout: 10000
    }).then(function (response) {
        if (response.ResultCode === '0') {
            if (image_arr.length != 0) {
                //this is recursively called upload function which returns jQuery promise (this works as intended)
                // the promise resolves with RequestId which I need later on
                return uploadImages(image_arr, image_arr.length, 0, response.RequestId)
            } else {
                //I would like this to return just this RequestId
                // added `return`
                return Promise.resolve(response.RequestId)
            }
        } else {
            // note `return`, removed `.promise()`
            return Promise.reject()        
        }
    }).fail(function (x, t, m) {
        if (t === "timeout") {
            // included `Promise`, chain `.reject()`
            // note, `return`
            return Promise.reject("Timeout: " + t);
        } else {
            // note `Promise.reject()`, added `return`
            return Promise.reject($.i18n('Error-RetrivingDataProblem'));
        }
    })
}

【讨论】:

  • 顺便说一句,我的印象是我不 return 解决/拒绝 (stackoverflow.com/questions/32536049/…)。还是没关系?
  • resolve(), reject()Promise 构造函数与 Promise.resolve(), Promise.reject() 不同
  • 我明白了。谢谢。我会调查的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-18
  • 1970-01-01
  • 1970-01-01
  • 2017-10-13
  • 1970-01-01
相关资源
最近更新 更多