【问题标题】:Call another function after complete one and make the result became a variable完成后调用另一个函数并使结果变为变量
【发布时间】:2018-01-09 08:20:40
【问题描述】:

我是 Javascript 世界的新手,到目前为止我只是在前端将 javascript 制作成一个简单的东西,这是我第一次尝试用 Javascript 制作一个逻辑程序,你能帮帮我吗?

假设我现在有 3 个函数通过 ajax 调用一个 json,称为函数 A、函数 B 和函数 C。

现在,我想让函数 A 在页面加载时准备好,然后在函数 A 完成获取 JSON 后,它将调用函数 B 运行,依此类推,直到函数 C 完成调用 JSON。

如果函数以某种方式出错/未能获取 json,它们将停止并且不会继续该过程(以调用其他函数)。即:
如果函数 A 失败,它将停止在函数 A 中,而不是继续它。如果函数 A 成功,那么它将调用函数 B,如果函数 B 失败,它将停止在函数 B 中而不是继续它。以此类推,直到函数 C 完成。

毕竟,我认为我需要在函数 A、函数 B 和函数 C 中通过 ajax 调用的结果(JSON)变成 Var A、Var B 和 Var C。

Jscript 可以做到这些吗?

【问题讨论】:

标签: javascript jquery json ajax


【解决方案1】:

用这么少的具体信息写一个答案真的很难,但我会努力的。

我认为您需要的是promises,因为它们允许您链接多个异步操作。一旦出现错误,链就会中断,从而调用错误处理程序(您可以选择指定)。

让我们定义一个函数functionA 来加载文件a.json

function functionA () {
  return new Promise(function (resolve, reject) {
    const xhr = new XMLHttpRequest();
    xhr.open('GET', 'a.json');
    xhr.onload = function () { resolve(xhr.response); };
    xhr.onerror = function () { reject('Could not load a.json'); };
  });
}

像这样使用这个函数:

functionA().then(function (response) {
  // this function is called as soon as the contents of the file are loaded
  // response contains the contents of the file
}).catch(function (errorMessage) {
  // this function is called whenever an error occurs
  // errorMessage contains the error message
});

假设您以与functionA 类似的方式定义函数functionBfunctionC。然后你可以像这样使用它:

let contentsOfFileA = '';
let contentsOfFileB = '';
let contentsOfFileC = '';
functionA()
  .then(fileA => {
    contentsOfFileA = fileA;
    return functionB();
  }).then(fileB => {
    contentsOfFileB = fileB;
    return functionC();
  }).then(fileC => {
    contentsOfFileC = fileC;
    // now, all files are loaded and you can use the variables 
    // contentsOfFileA, contentsOfFileB and contentsOfFileC
  }).catch(error => console.log('An error occurred:', error));

上面的 sn-p 包含非常冗余的代码。使用Promise.all,您可以缩短它:

Promise.all(functionA(), functionB(), functionC())
  .then([fileA, fileB, fileC] => {
    // do something with the three files' contents
  }).catch(error => console.log('An error occurred:', error));

当然,functionAfunctionBfunctionC 所做的事情非常琐碎。要加载 JSON 文件,您还可以使用fetch API

Promise.all(['a.json', 'b.json', 'c.json'].map(file => fetch(file)))
  .then(responses => Promise.all(responses.map(r => r.json())))
  .then(([fileA, fileB, fileC]) => {
    // do something with the three files' contents
  }).catch(error => console.log('An error occurred:', error));

【讨论】:

    【解决方案2】:

    你为什么不继续使用 jquery?

    $(document).ready(function() { //because you want to execute after page load.
    
    $.when(function a()).then(function b());
    }
    //For Ajax 
    function a(){
       // your code function a
    }
    function b(){
       // your code function b
    }
    
    $.ajax({
       url:a(),
       success:function(){
       b();
    }
    })
    

    此代码未经测试,但可以试一试。

    【讨论】:

      【解决方案3】:
      function toCall(callback){
       //do all the stuff you want to
       return callback();
      }
      

      您的函数将返回回调的值。 例如:

      let number = toCall(function(){ return 1; });

      【讨论】:

        猜你喜欢
        • 2019-12-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-10-23
        • 2018-04-29
        • 2020-11-07
        相关资源
        最近更新 更多