【发布时间】: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