完成后调用另一个函数,使结果成为变量

时间:2017-08-02 08:16:12

标签: javascript jquery json ajax

我是Javascript世界的新手,到目前为止我只是在前端使用javascript来做一个简单的事情,这是我第一次尝试用Javascript制作逻辑程序,你能帮助我吗?

让我说我现在有3个函数通过ajax调用json调用函数A,函数B和函数C.

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

如果函数出现错误/无法获得json,它们将停止并且不继续进程(调用其他函数)。即: 如果功能A失败,它将在功能A中停止,而不是继续它。如果函数A成功,则它将调用函数B,如果函数B失败,它将在函数B中停止而不是继续它。依此类推,直到功能C完成。

之后,我认为我需要通过函数A,函数B和函数C中的ajax调用的结果(JSON)变为Var A,Var B和Var C.

使用Jscript可以解决这个问题吗?

3 个答案:

答案 0 :(得分:1)

function toCall(callback){
 //do all the stuff you want to
 return callback();
}

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

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

答案 1 :(得分: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
});

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

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));

上面的代码段包含非常冗余的代码。使用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 :(得分:1)

为什么不继续使用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();
}
})

此代码未经过测试,但试一试。

相关问题