我编写了这段代码,从ajax调用中获取Json。我需要使用javascript promise(在2秒后解决)和.then()方法来处理响应(成功,错误)。我在网上阅读了一些资料,但不知道从哪里开始。有人可以帮我吗?谢谢
function jsonResult(spaceName){
var baseUrl = "BaseUrl";
$.ajax({
url:baseUrl + "/api/request/url",
type:"GET",
dataType: "json",
error: function(xhr,status,error) {
console.log(JSON.stringify(error));
},
success: function(response){
getResult(response)
}
});
}
答案 0 :(得分:0)
您只需要更新函数以返回一个Promise,然后在成功和错误方法中分别调用resolve和reject。这是从MDN中提取的示例:
function myAsyncFunction(url) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.onload = () => resolve(xhr.responseText);
xhr.onerror = () => reject(xhr.statusText);
xhr.send();
});
}
您可以在此处了解更多信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
这是示例代码的简单实现:
function jsonResult(spaceName){
var baseUrl = "BaseUrl";
return new Promise((resolve, reject) => {
$.ajax({
url:baseUrl + "/api/request/url",
type:"GET",
dataType: "json",
error: function(xhr,status,error) {
reject(JSON.stringify(error));
},
success: function(response){
resolve(response);
}
});
});
}
答案 1 :(得分:0)
您可以在调用此函数时向用户返回一个承诺,该承诺将在成功回调中解析,并在像这样的错误回调中被拒绝
function jsonResult(spaceName){
var baseUrl = "BaseUrl";
return new Promise((resolve, reject) => {
$.ajax({
url:baseUrl + "/api/request/url",
type:"GET",
dataType: "json",
error: function(xhr,status,error) {
console.log(JSON.stringify(error));
reject(error);
},
success: function(response){
resolve(getResult(response));
}
});
}
}
// Usage
jsonResult(someInput).then(response => {
// success
})
.catch(error => {
// error
});
答案 2 :(得分:0)
jQuery 3.0 is Promises/A+ compatible,所以只需删除错误/成功并执行then/catch
function jsonResult(spaceName) {
var baseUrl = "BaseUrl";
$.ajax({
url:baseUrl + "/api/request/url",
type:"GET",
dataType: "json"
}).then(console.log, console.error)
}
alternativ是本地获取API ...
fetch(baseUrl + "/api/request/url")
.then(res => res.json())
.then(console.log)