我试图从异步函数调用返回一个值,我理解,从this这样的帖子中你不能使用return。但是,暗示我应该能够通过正确使用回调和承诺来实现这一目标。不幸的是,我很难确定如何处理下面的问题。
在这里,我想返回一个我从AJAX调用中获取的URL值。
function getGithubURL(name){
var ghUserURL = 'https://api.github.com/users/bullcitydave?client_id=-----&client_secret=------';
var jsPromise = Promise.resolve($.getJSON(ghUserURL));
var avatar;
jsPromise.then(function(data) {
avatar = data.avatar_url;
console.log(avatar); // I have the correct value here
});
return avatar; // how do I return it correctly?
};
答案 0 :(得分:1)
您不能在同步函数中返回从异步操作获取的值。异步操作直到稍后才会完成,因此当getGithubURL()
函数返回时它仍然不可用。这是一个时间问题,只是javascript无法做到的事情。
您可以通过重新构建使用承诺的方式来解决问题。你想要做的是让.then()
处理程序成为最终数据的使用者。这样您就可以通过promise结构传回数据。您还希望利用$.getJSON()
已经返回的承诺 - 无需在此创建您自己的承诺。
这是一种方法。
getGithubURL("bullcitydave").then(function(url) {
// you can use the avatar url here
});
function getGithubURL(name){
var ghUserURL = 'https://api.github.com/users/bullcitydave?client_id=-----&client_secret=------';
return $.getJSON(ghUserURL).then(function(data) {
return data.avatar_url;
});
};
您致电$.getJSON()
。它返回一个promise,您可以在其中添加.then()
处理程序,以便提取所需的实际数据。从.then()
处理程序,您返回所需的最终数据。 $.getJSON().then()
序列会创建一个新的承诺,即您从getGithubURL()
函数返回的承诺,并且在getJSON().then()
序列完成之前不会解析。这会将您的头像URL显示给外部.then()
处理程序,如代码中所示
上方。
或者,如果getGithubURL()
函数的调用者不打算使用promises,那么你可以让你的函数接受这样的回调:
getGithubURL("bullcitydave", function(url) {
// you can use the avatar url here
});
function getGithubURL(name, fn) {
var ghUserURL = 'https://api.github.com/users/bullcitydave?client_id=-----&client_secret=------';
$.getJSON(ghUserURL).then(function(data) {
// call the callback and pass it the avatar url
fn(data.avatar_url);
});
};