简体   繁体   中英

How do i handle callback function response?

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.

You can use async/await here. Like

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

}();

Make sure your yourAsyncCallBack returns a promise.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM