簡體   English   中英

我該如何處理回調函數響應?

[英]How do i handle callback function response?

我了解異步性質的行為,但是我的其他同步代碼取決於回調的返回值。 我如何重新格式化代碼以實現這一目標。

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

感謝您的寶貴時間和建議。

您可以async/await此處使用async/await 喜歡

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

}();

確保yourAsyncCallBack返回了一個yourAsyncCallBack

因為代碼中的一個(或幾個)函數是異步的,所以回調函數會延遲運行,但是您的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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM