0

I understand the behavior of asynchronous nature however my other synchronous code depend on return value from the callback. How can i reformat the code to achieve that.

Module A

export function processData(callback){
    var value = "TEST";
    callback(value);
}

Module B

import { processData } from './A.js';

var resultValue = ''; /*global variable */
function dataFetcher(){

    processData(getData);

    // define callback
    function getData(x){
        console.log(" I got x : "+x); /* prints TEST */
        sendData(x);
    }

    //called from callback function
    function sendData(data){
        resultValue = data;
    }
}

console.log(" print resultValue : "+resultValue); /* prints empty string */

Thanks for your time and suggestions.

Mad-D
  • 4,479
  • 18
  • 52
  • 93
  • 1
    Your code is tagged with [tag:es6-promise], but you're not using promises. Maybe you should take a look at them. Along with `async` and `await`. – cHao Jun 06 '18 at 19:52
  • 1
    Your example is overly simplified, there's nothing asynchronous in there so it's hard to understand what is actually happening. – Bergi Jun 06 '18 at 19:52
  • 2
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Heretic Monkey Jun 06 '18 at 19:54
  • Possible duplicate of [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – Patrick Roberts Jun 06 '18 at 19:57

2 Answers2

0

You can use async/await here. Like

async function() {
 resultValue = await yourAsyncCallBack();
  console.log(resultValue);

}();

Make sure your yourAsyncCallBack returns a promise.

Muhammad Usman
  • 10,039
  • 22
  • 39
0

Because one(or few) of functions in your code is asynchronous the callback function run with delay, but your console.log called in main thread immediately. So to solve this you may change the code like this:

import { processData } from './A.js';

var resultValue = ''; /*global variable */
function dataFetcher(){

    processData(getData);

    // define callback
    function getData(x){
        console.log(" I got x : "+x); /* prints TEST */
        sendData(x);
    }

    //called from callback function
    function sendData(data){
        resultValue = data;
        done();
    }
}

function done() {
  console.log(" print resultValue : "+resultValue);
}
Oleg Imanilov
  • 2,591
  • 1
  • 13
  • 26