Async Function and Promise [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 2 years ago.
I am a newbie in JavaScript, trying to implement code to connect to MySQL. I am using Promise along with Async/Await function. My goal is to get the return value of the Promise object.
However, I have read and tried every possible way but still failed to understand how the Asynchronous function works in JavaScript as the return value of the function getData() still return an object
Promise { < pending > }
I also tried to use then but it still returns the same result. I would really appreciate it if someone can show me what I have misunderstood or where I did wrong in this function. Thank you!
Here is my JS code:
function test_connection() {
var connection = #MySQLConnectionObject;
return new Promise((resolve, reject) => {
connection.connect((error, result) => {
if (error) {
reject(error)
} else {
connection.end();
resolve("Successfully Connected!");
}
});
});
}
async function getData() {
var result = await test_connection()
return result;
}
var result = getData();
console.log(result);

Related

Return value instead of promise without await [duplicate]

This question already has answers here:
How can I access the value of a promise?
(14 answers)
Why is my asynchronous function returning Promise { <pending> } instead of a value?
(9 answers)
Closed 1 year ago.
As parent function does not support async. I need to make call without await and get return value. As suggested on most of the posts, applied promise with then and returning value. But it prints as "promise" instead of return "value".
Can you please share, how to achieve return value instead of promise.
code sandbox:
https://codesandbox.io/s/await-without-async-and-return-value-qbs7t?file=/src/index.js
await isEnable(data) {
try {
...
return true;
}
catch (e) {
console.error(e);
}
}
}
const getEnableStatus=(data) =>{
return isEnable(data).then((result) =>
{console.log(result); return result;}); //this prints correctly but, need this in return result.
}
console.log(getEnableStatus(data)); //it always print 'promise'. how to get value here instead of promise.
Pass in a callback to the getEnableStatus function, and then call it with the returned data.
// Mock function that resolves after
// two seconds
function isEnable() {
return new Promise((res, rej) => {
setTimeout(() => res('Hallo!'), 2000);
});
}
// Accept a callback, and call it with the data
function getEnableStatus(data, callback) {
isEnable(data).then(callback);
}
// The callback logs the data
getEnableStatus('data', function (data) {
console.log(data);
});

Issue in using async/await function [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Use Async/Await with Axios in React.js
(3 answers)
Closed 1 year ago.
I am new to this whole async function concept. Here is the function that I want to use:
async function fetchData() {
try {
const resultRes = await fetch("https://www.breakingbadapi.com/api/characters?category=Better+Call+Saul");
const result = await resultRes.json();
return result;
} catch (error) {
console.error(error);
}
}
And this is what function call looks like:
const Data = fetchData();
Now I want to console.log(Data) with the array that is returned but intead it shows as a promise object.
How should I use this function as using it with .then messes up my whole app as the containing file is a react component?

Why is this DB function returning undefined? [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 2 years ago.
I'm trying to make a function where I can easily call my MongoDB.
This is the function code/hanlder:
let get = {};
get.getGuildData = (id) => {
const guildData = require('./models/guilds.js')
guildData.findById(id).then(async (data) => {
return guildData.findById(id)
})
};
module.exports = { get }
This is where I am calling the function:
const getGuild = bee.get.getGuildData(msg.guildID)
console.log(getGuild)
It returns undefined, but the console.log on the actual function returns the correct thing:
Let me know if anyone knows a solution to this.
I can not find an answer in this post. How do I return the response from an asynchronous call?
You cannot return the data, because it doesn't exist yet. What you can do is return a promise. guildData.findById(id) apparently is already returning a promise which resolves to the data, so you do not need to call .then on it to create a new promise.
get.getGuildData = (id) => {
const guildData = require('./models/guilds.js')
return guildData.findById(id);
};
Since the function is now returning a promise, any code that calls it will need to work with promises. Either call .then on the promise:
bee.get.getGuildData(msg.guildID)
.then(data => {
console.log(data);
});
Or if you're in an async function, use await:
async function someFunction() {
const data = await bee.get.getGuildData(msg.guildID);
console.log(data);
}

Code execution does not wait for value returned [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
I have following controller and code execution does not wait for the function to bring back values. So some lines of code fail as they are still undefined. How to make sure line execution is in sync.
Also Note: caller function is inside a for loop.
A Controller.js
for (var i=0; i< parseObj.length; i++){
callerFunc: function() {
vc._getValues(A, B, C).then(function (data) {
var vendorNo = data.vendorNo;
var vendorName = data.vendorName
});
// lines of code
}
_getValues: function(A, B, C){
var filters = [
.....
];
var vc = this;
return new Promise(function (resolve, reject) {
service.getDataByFilters(vc, filters,
function (data) {
resolve(data);
},
function (error) {
reject();
}
);
});
the problem is that you need to wait for the result. Service.getMaterial is returning a Promise so when you try to execute the line of code var x = data.Vendor; the variable data is not yet defined.
What you can do is to just call a function inside the promise result (the then function).
I would suggest you learn a little bit more about:
Promise
async/await pattern
I also would like you to know that promise/async-await are not supported by IE in general if I'm not wrong ;)

Node.js Function Returns 'undefined' [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
The following Node.js code prints 'undefined', even though it found the file.
var fileFound = function() {
fs.readFile('public/images/acphotos/Friedrich-EL36N35B.jpg', function(err, data) {
if (err) {
console.log(err);
return false;
} else {
return true;
}
});
}
console.log("Return value: " + fileFound());
How would I rewrite it? I don't fully understand the solution in the other thread I was shown.
Because the return statements are inside the callback passed into fs.readFile.
the fileFound function never returns anything, therefore you get undefined.

Categories

Resources