我有两个功能,
function getRequest(url, api_key, callback) {
$.ajax({
url: url,
contentType: 'application/json',
type: 'get',
beforeSend: function(xhr){
xhr.setRequestHeader('Authorization', 'Bearer ' + api_key);
},
success: function(response) {
callback(response);
},
error: function(error) {
console.log(error);
document.getElementById("droplets").textContent = error;
}
});
}
function getDroplets(url, api_key) {
var request = getRequest(url, api_key, function(response) {
var droplets = response.droplets;
var numDroplets = droplets.length;
return {
droplets: droplets,
numDroplets: numDroplets
};
});
alert(request);
}
我希望有另一个功能,让我们称之为listDroplets
,它会调用getDroplets()
并操纵从它返回的数据。我不确定如何执行此操作,因为getDroplets
中有异步调用。
async function listDroplets() {
await getDroplets(api_url, api_key);
alert(request.numDroplets);
}
答案 0 :(得分:2)
以下是您的函数如何返回可以在异步等待函数中使用的对象的承诺:
function getRequest(url, api_key, callback) {
//to escape terrible jQuery Deferred and comfortably continue in Promise land
// you can do
// const deferred = $.ajax(...); return Promise.resolve(deferred)
return $.ajax({//return promise like object
url: url,
contentType: 'application/json',
type: 'get',
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', 'Bearer ' + api_key);
}
});
}
function getDroplets(url, api_key) {
return getRequest(url, api_key)//return promise like object
.then(function (response) {//
var droplets = response.droplets;
var numDroplets = droplets.length;
return {
droplets: droplets,
numDroplets: numDroplets
};
})
.catch(function (error) {//implement error if something goes wrong
console.log(error);
document.getElementById("droplets").textContent = error;
});
}
async function listDroplets() {
//depending on how old your jQuery is you may want to do this:
// await Promise.resolve(getDroplets(api_url, api_key));
const request = await getDroplets(api_url, api_key);
//note that if something goes wrong then request is undefined (depending on jQuery version)
alert(request.numDroplets);
}