How to Return Value from an Asynchronous Callback Function

How to return value from an asynchronous callback function?

This is impossible as you cannot return from an asynchronous call inside a synchronous method.

In this case you need to pass a callback to foo that will receive the return value

function foo(address, fn){
geocoder.geocode( { 'address': address}, function(results, status) {
fn(results[0].geometry.location);
});
}

foo("address", function(location){
alert(location); // this is where you get the return value
});

The thing is, if an inner function call is asynchronous, then all the functions 'wrapping' this call must also be asynchronous in order to 'return' a response.

If you have a lot of callbacks you might consider taking the plunge and use a promise library like Q.

Inside async function, returning value from a callback function returns Promise(undefined)

make your query function return a Promise

function query(sql, args) {
return new Promise(function (resolve , reject) {
this.connection.query(sql, args, (err, rows) => {
if (err)
reject(err);
else
resolve(rows)
});
});
}


//calling the function here
query("select 1")
.then((row) => console.log("Rows",row)) // Rows undefined
.catch((e) => console.log(e));

Node.JS function to return the value of a async callback function

Due it's asynchronous code You've to use callback to get data.

You think if You use async package it will help You do return result?

  • No, You cannot.

Async package is helpful to get rid of callback-hell, when You've many functions that use result of previous function.

In Your case You don't need async.

Please read or watch tutorials about nodejs asynchronous behavior. For example this tutorial series: timeline 03:00 where explains blocking vs non-blocking code

So to get data after query execution is only this way:

mysql_connection.connect();

function get_all_channels_by_order(callback){
mysql_connection.query("SELECT * FROM channels ORDER BY listorder ASC", callback);
}

get_all_channels_by_order(function(err, result) {
if(err) {
console.error(err);
return;
}

console.log(result);
});

How to await for a callback to return?

async/await is not magic. An async function is a function that can unwrap Promises for you, so you'll need api.on() to return a Promise for that to work. Something like this:

function apiOn(event) {
return new Promise(resolve => {
api.on(event, response => resolve(response));
});
}

Then

async function test() {
return await apiOn( 'someEvent' ); // await is actually optional here
// you'd return a Promise either way.
}

But that's a lie too, because async functions also return Promises themselves, so you aren't going to actually get the value out of test(), but rather, a Promise for a value, which you can use like so:

async function whatever() {
// snip
const response = await test();
// use response here
// snip
}

How to return values from async functions using async await from a callback function?

I'm interested in using await / async to clean out the code

There are two steps to this: promisification and async. Your code is getting confused because it's skipping the first step.

Promisification creates very simple promise-returning wrapper functions around the callback functions. For example, if t is an instance of a Trello class:

Trello.prototype.postAsync = (url, data) => new Promise((resolve, reject) => {
this.post(url, data, (err, result) => {
if (err) { reject(err); }
else { resolve(result); }
});
});

The second step is to write your async/await logic, using promise-returning functions and not callbacks. Since they are promise-returning, they code is much more natural:

const board = await t.postAsync("1/board", {
name: project.name,
desc: project.description,
defaultLists: false
});
console.log("board" + board);

//create labels
let highId;
try {
highId = await t.postAsync("1/labels", {
name: 'High',
color: 'red',
idBoard: board.id
});
} catch (err) {
console.log(err || 'High label created');
return;
}

The promisification step is tedious and repetitive. There are some libraries that can automate callbacks-to-promises, most notably Bluebird.

How to return values from async functions using async-await from function?

You cant await something outside async scope. To get expected result you should wrap your console.log into async IIFE i.e

async function getData() {
return await axios.get('https://jsonplaceholder.typicode.com/posts');
}

(async () => {
console.log(await getData())
})()

Working sample.

More information about async/await

Since axios returns a promise the async/await can be omitted for the getData function like so:

function getData() {
return axios.get('https://jsonplaceholder.typicode.com/posts');
}

and then do same as we did before

(async () => {
console.log(await getData())
})()


Related Topics



Leave a reply



Submit