Home > OS >  Return value from callback
Return value from callback

Time:01-11

I have value inside callback function and couldn't return successfully.

async pos(convertedCodeDBSearch) {
    var dd;
    const x =  await idealPostcodes.lookupAddress(convertedCodeDBSearch, function (error, searchResults)  {
      return searchResults.result.hits[1];
    });
    console.log('x', x);
  }

I need to return searchResults.result.hits[1]; from function. Here is the code, Thank you.

CodePudding user response:

I imagine you are using this npm package or a fork of it. If this is the case, you should revise your logic, because the call to lookupAddress does not return a value by itself, meaning that the x in your code will always be undefined.

Since you are already working with async functions, my suggestion is using the Node helper util.promisify to extract the result from the callback function into a promise. This promise can be awaited to get the success value of the original callback (here searchResults).

const { promisify } = require('util');

async pos(convertedCodeDBSearch) {
    var dd;
    const searchResults = await promisify(idealPostcodes.lookupAddress.bind(idealPostcodes))(convertedCodeDBSearch);
    return searchResults.result.hits[1];
}

CodePudding user response:

Not sure if it'll solve you're problem, but why don't you get rid of the callback entirely and utilize the async/await syntax to it's fullest?

async pos(convertedCodeDBSearch) {
    var dd;
    try {
        const x =  await idealPostcodes.lookupAddress(convertedCodeDBSearch);
        const results = x.result.hits[1];
        console.log(`The results are: ${results}`);
        return results;
    } catch (e) {
        console.error("Something went wrong")
    }
}

CodePudding user response:

You can use Promise to achieve that:

async pos(convertedCodeDBSearch) {
  var dd;
  const x = await new Promise(async (resolve, reject) => {
    await idealPostcodes.lookupAddress(convertedCodeDBSearch, function (error, searchResults)  {
      resolve(searchResults.result.hits[1]);
    });
  })
  console.log('x', x);
}
  •  Tags:  
  • Related