简体   繁体   English

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

[英]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 模块A

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

Module B 模块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. 您可以async/await此处使用async/await Like 喜欢

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

}();

Make sure your yourAsyncCallBack returns a promise. 确保yourAsyncCallBack返回了一个yourAsyncCallBack

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. 因为代码中的一个(或几个)函数是异步的,所以回调函数会延迟运行,但是您的console.log立即在主线程中调用。 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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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