我如何处理回调函数响应?

时间:2018-06-06 19:48:19

标签: javascript asynchronous callback synchronous

我理解异步性质的行为,但是我的其他同步代码依赖于回调的返回值。我如何重新格式化代码来实现这一目标。

模块A

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

模块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 */

感谢您的时间和建议。

2 个答案:

答案 0 :(得分:0)

您可以在此处使用async/await。像

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

}();

确保您的yourAsyncCallBack返回承诺。

答案 1 :(得分:0)

因为代码中的一个(或几个)函数是异步的,所以回调函数会延迟运行,但是你的console.log会立即在主线程中调用。所以要解决这个问题,你可以改变这样的代码:

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);
}
相关问题