0

As the title says, is it possible for me to place the following async function:

callArgos("fifa 17", function(title, price) {
    console.log("Argos title " + title + " price " + price);
})

within another function say:

     function foo() {
       callArgos("fifa 17", function(title, price) {
          console.log("Argos title " + title + " price " + price);
       })
     }  

And then call function foo, to return title and price, and assign these to global variables?

I have three separate async functions which obtain prices from three different websites and the prices are returned using callbacks to those functions. I wish to then assign the values being returned to global variables, in order to compare all three prices. I'm not sure if it's possible in JS and Node.js.

What do you guys think?

user1156596
  • 601
  • 1
  • 10
  • 29
  • Use call backs, pass reference of 2nd function in 1st function and call it after execution of 1st one. – Shubham Dec 13 '16 at 11:13
  • if this is jquery `ajax` function, then you can just call the `.done` on those methods, else you need to create a `deferred` object for user defined function and resolve those `deferred` objects to notify the subscriber ,https://api.jquery.com/jquery.deferred/ – dreamweiver Dec 13 '16 at 11:19
  • You really want to use promises (and `Promise.all`) for this – Bergi Dec 13 '16 at 11:42
  • *it possible for me to place the following async function* YES!! If you have a time machine that is. –  Dec 13 '16 at 12:11

1 Answers1

-2

Sure. Have a look at this fiddle. Does this work for you?

https://jsfiddle.net/9djnexrv/

// Prices will be stored here
var prices = [];

// Dummy-function to mock async behaviour
function callArgos(someString, someCallback) {
  setTimeout(function() {
    someCallback(someString, 42);
  }, Math.random()*100);
}

// Actual function
function foo() {
  callArgos("fifa 15", function(title, price) {
    prices[0] = price;
    console.log("Argos title " + title + " price " + price, prices);
  });

  callArgos("fifa 16", function(title, price) {
    prices[1] = price;
    console.log("Argos title " + title + " price " + price, prices);
  });

  callArgos("fifa 17", function(title, price) {
    prices[2] = price;
    console.log("Argos title " + title + " price " + price, prices);
  });
}  

// Execute function
foo();
Fabian Scheidt
  • 372
  • 3
  • 10