How do I change below callback code to async/await version? [duplicate] - javascript

This question already has answers here:
How do I convert an existing callback API to promises?
(24 answers)
Closed 1 year ago.
I'm trying to convert this callback to async/await but seems I can't figure out how to do it.
function getTotalUsersCount(callback) {
User.count({}).exec((err, count) => {
if (err) {
return callback(null, 0);
}
return callback(null, count);
});
},
Also I want to change the
User.count({}).exec((err, count)
to this
const count = await User.count();

If you are using Mongoose then it should work.
function getTotalUsersCount() {
return User.count({})
};
async function test() {
const result = await getTotalUsersCount();
}
Almost every Mongoosecall returns promise if you don't pass the callback, so you can use async/await syntax in any async function.
If you want you can wrap the function in a promise manually.
function getTotalUsersCount() {
return new Promise((res, rej) => {
User.count({}).exec((err, count) => {
if (err) {
return rej(err);
}
return res(count)
});
});
};
And you still should be able to call this funciton in the same way as I shoved above in the test function.

Related

how to use async await correctly [duplicate]

This question already has answers here:
How to make a promise from setTimeout
(8 answers)
How to handle multiple async requests?
(2 answers)
Closed 6 months ago.
this is regarding async await and promises. I am not very good at this so I guess i´m missing something. My code is meant to execute the first greetings function which it does. But then only once its done (and only then) it should execute any consecutive functions.
I have tried setting it up in many ways but either the second function doesn't execute or it executes before completion of the first.
Here is my code:
const greetingDivs = [firstDiv, secondDiv, thirdDiv, fourthDiv, fifthDiv]
let y = 0
function greetings() {
if (y != greetingDivs.length) {
setTimeout(() => {
consoleOutput.appendChild(greetingDivs[y])
y++
}, 500)
setTimeout(() => {
greetings()
}, 500)
}
if (y == greetingDivs.length) {
return console.log('Greetings are done!')
}
}
function secondFunction() {
console.log('I have waited')
}
async function consoleOn() {
const result = await greetings()
if (result) {
secondFunction()
}
}
consoleOn()

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);
});

JS wait for subscription results [duplicate]

This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 1 year ago.
I am trying to figure out the best way to wait on the results of a subscription where I am passing in a callback. For example let's say I have the following:
function someMethod() {
let someResult = null;
someSubPub.subscribe(someTopic, someKey, someValue, (someResponse) => {
someResult = //do stuff in the callback with someResponse
});
return someResult;
}
I'm not quite sure how await would correctly work in this situation, aka blocking inside a callback.
Async/Await are nice, but sometimes it's simpler to think about the Promise construct that async/await abstracts away.
I suggest:
function someMethod() {
return new Promise((resolve, reject) => {
someSubPub.subscribe(someTopic, someKey, someValue, () => {
const someResult = //do stuff in the callback
resolve(someResult);
});
});
}
If you don't want to work with promises directly, you can wrap someSubPub.subscribe to return a promise
function someSubPubSubscribePromise(topic, key, value) {
return new Promise((resolve, reject) => {
someSubPub.subscribe(topic, key, value, resolve);
});
}
async function someMethod() {
await someSubPubSubscribePromise(someTopic, someKey, someValue);
const someResult = //do stuff in the callback
return someResult;
}
In either of those examples, you can do const result = await someMethod() (you can await both async methods and regular methods that return a promise)
One thing to consider: usually a pub/sub interface can call the callback multiple times. An async method / a method returning a promise can only resolve or reject exactly once. Probably you should be unsubscribing in the callback after you've responded to the event once?

Async Function and Promise [duplicate]

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);

waiting for async callback, then return [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
Here is a function that I would like to call for its return value, and in that function I would like to use an async call that would set a flag to work with later on:
function getSomething() {
var isOk;
myAsyncFunction(function(data) {
if (data === 'foo') {
isOk = true;
}
});
//...
if (isOk) {
return true;
}
}
I would want to use getSomething() like this:
if (getSomething()) {...}
I know that it won't pause the execution of this function to wait for my async call to finish. I also know that the return true statement should not be in the callback of the async function. But how can I wait for the async function's callback? Should I transform my getSomething() call to a promise or is there another way? And how would be the call of getSomething() look like if I'd use promises? Thanks in advance!
You can use JavaScriptPromise
var promise = new Promise(function(resolve, reject) {
if (/* everything turned out fine */) {
resolve("worked!");
}
else {
reject(Error("broke"));
}
});
How to use
promise.then(function(result) {
console.log(result); // "worked!"
}, function(err) {
console.log(err); // Error: "broke"
});
For more information you can visit this link Promise

Categories

Resources