-2

I am new to Javascript world, so far i just make javascript to a simple things in front end, this is first time i trying to make a logical procedure with Javascript,can you help me?

Lets said i have 3 function right now to call a json via ajax called function A, function B, and function C.

And now, i want to make Function A ready when a page onload, then after Function A is finish get the JSON it will call Function B to run, and so on until Function C finish call the JSON.

If somehow the Function got an error/failed to get a json they will stop and not continue the process (to call other Function). I.e :
If Function A failed, it will stop in Function A, not continue it. If Function A success then it will call Function B, and if Function B failed, it will stop in Function B instead continue it. And so on until Function C complete.

And after that all, i think i need the result(JSON) that called via ajax in Function A, Function B, and Function C to became Var A, Var B, and Var C.

Is it possible to this things with Jscript ?

vl14b
  • 85
  • 2
  • 14
  • 1
    Possible duplicate of [Execute jquery function after another function completes](https://stackoverflow.com/questions/19674380/execute-jquery-function-after-another-function-completes) – Carsten Løvbo Andersen Aug 02 '17 at 08:17
  • Welcome to Stack Overflow! Please take the [tour], have a look around, and read through the [help], in particular [*How do I ask a good question?*](/help/how-to-ask) Code is work 1024 words. Try to do what you've described, with thorough research, debugging, etc. **If** you get stuck, post a question with a [mcve] of your code saying what specific problem you're having and what you've done to diagnose/fix it, and people will be glad to help. – T.J. Crowder Aug 02 '17 at 08:18

3 Answers3

2

It's really hard to write an answer with so little concrete information, but I will try.

I think what you need are promises, as they allow you to chain multiple asynchronous actions. As soon as there is an error, the chain will break, causing an error handler (that you can optionally specify) to be called.

Let's define a function functionA that loads the file 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'); };
  });
}

Use this function like this:

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

Let's say you define the functions functionB and functionC in a similar way to functionA. You could then use it like this:

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

The snippet above contains very redundant code. Using the Promise.all, you can shorten it:

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

Of course, what functionA, functionB and functionC are doing is very trivial. To load a JSON file, you can also use the 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));
PeterMader
  • 6,987
  • 1
  • 21
  • 31
1
function toCall(callback){
 //do all the stuff you want to
 return callback();
}

your function wil return the value of the callback. for example:

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

locomain
  • 185
  • 1
  • 15
1

Why don't you go ahead and use 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();
}
})

This code is not tested but gives it a try.

Ravi Ranjan
  • 105
  • 1
  • 13