Yas*_*dia 4 javascript ajax jquery promise
我想解决一个诺言,这反过来又使一个ajax调用。无论ajax调用是否成功,都应解决诺言。我尝试了以下代码段:
new Promise(function(resolve, reject) {
$.ajax({
url: "nonExistentURL",
headers: {
"Content-Language": "en"
},
async: true,
type: "DELETE",
contentType: "application/json",
crossDomain: true,
dataType: "json"
}).done(function(oSuccessData) {
debugger;
resolve(oSuccessData);
}).fail(function(oData) {
debugger;
resolve(oData);
});
}).then(function(oData) {
debugger;
}).catch(function(err) {
debugger;
});Run Code Online (Sandbox Code Playgroud)
但是,这似乎总是在进入catch回调。为什么不进入then回调?
实际上是由于您在fail回调中收到的参数。它是一个XHR可行承诺类型对象。由于您要用一个rejected诺言来解决该功能,因此它就变成了catch块。
您可以将error对象包装在另一个对象中说{ err: oData },然后then回调将得到正确解析。
new Promise(function(resolve, reject) {
$.ajax({
url: "nonExistentURL",
headers: {
"Content-Language": "en"
},
async: true,
type: "DELETE",
contentType: "application/json",
crossDomain: true,
dataType: "json"
}).done(function(oSuccessData) {
console.log("Done callback: Resolving the promise with Data");
resolve(oSuccessData);
}).fail(function(oErr) {
console.log("Fail callback: Resolving the error");
resolve({ err: oErr });
});
}
).then(function(oData) {
console.log("Then Callback");
}).catch(function(err) {
console.log("Catch the error");
});Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
58 次 |
| 最近记录: |