0

I'm trying pass "t_id" value to the next function (func_B), when I execute the below code i'm getting "Undefined" message in the response. Can you help me to correct the below script ?

function func_A(){
        request(options, (error, response, body) => {
            const data = JSON.parse(response.body)
            t_id= String(data.result[0].test_id.value)
            console.log('Response id ' + t_id)
            return t_id
        });
    }

function func_B(id){
    var names = func_A();
    console.log('function2 response ' + names);
}
func_B(id)

Response:

Response id B12T5343J989L
function2 response undefined
itgeek
  • 549
  • 1
  • 15
  • 33

1 Answers1

1

This a classic case of an asynchronous gotcha.

This link kind of describes the problem and solution https://www.freecodecamp.org/news/async-await-in-javascript/

Below is an example of how to get the value using a callback, but it might be best to look into async/await, which uses a more natural looking flow to handle asynchronous calls

function func_A(callback) {
  request(options, (error, response, body) => {
    const data = JSON.parse(response.body)
    t_id= String(data.result[0].test_id.value)
    console.log('Response id ' + t_id)
    callback(t_id)
  });
}

function func_B(id){
  func_A(function (names) {
    console.log('function2 response ' + names);
  });
}
func_B(id)
Kieran101
  • 565
  • 5
  • 18