等待API调用以Javascript完成后再继续

等待API调用以Javascript完成后再继续,第1张

等待API调用以Javascript完成后再继续

每天要问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);


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5622801.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-15

发表评论

登录后才能评论

评论列表(0条)

保存