每天要问100次并且似乎不可能有一个答案的问题。
该调用是异步的,因此不可能一步完成。您期望的基本示例。
function one() { var a = 1; return a;}alert( one() );
实际发生了什么:
function one() { var a; window.setTimeout( function() { a = 1; }, 2000); return a; //This line does not wait for the asynchronous call [setTimeout/ajax call] to run. It just goes!}alert( one() );
您需要做的是将其分为两部分。
function one( callback ) { window.setTimeout( function(){ //acting like this is an Ajax call var a = 1; callback(a); },2000);}function two( response ) { alert(response);}one( two );
因此,在您的情况下,您需要分解代码以分两个部分来处理它。
function makeCall( callback ) { var body = 'Test post'; FB.api('/me/feed', 'post', { message: body }, function (response) { if (!response || response.error) { var finalresponse = response.error; } else { finalresponse = 'Post ID: ' + response.id; } callback(finalresponse); });}function processResponse( response ) { console.log(response);}makeCall(processResponse);
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)