How to turn this callback into a promise using async/await?
How to use
async
/await
to turn this callback function into a promise?
You don't. As usual, you use the new Promise
constructor. There's no syntactic sugar for that.
function loadImage(url) {
return new Promise((resolve, reject) => {
const img = new Image();
img.addEventListener('load', () => resolve(img));
img.addEventListener('error', reject); // don't forget this one
img.src = url;
});
}
How to use
await
/async
to log the value only when the photo has loaded and the width and height is already available?
You can do
async function getImageData(url) {
const img = await loadImage(url);
return { width: img.naturalWidth, height: img.naturalHeight };
}
async function ready() {
console.log(await getImageData(this.url))
}
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));
How can an async function await the callback of an inner async function?
You'll want to wrap the callback in a new Promise
and return the resolve
or reject
. This way, you can await
your call to await getPublicKey()
and it will not resolve until the callback is done.
async getPublicKey(): Promise<string> => {
return new Promise((resolve, reject) => {
const callback = async (err: any, key: any) => {
if (!err) {
resolve(key.result);
}
else {
reject(err);
}
};
this.web3js.currentProvider.sendAsync({
jsonrpc: '2.0',
method: 'eth_getEncryptionPublicKey',
params: [this.account],
from: this.account,
}, callback);
})
})
}
Changing my callbacks, promise to async await
How to convert this above code using async await?
async/await
is not a replacement for promises, it is a replacement for then()
and catch()
. You'd still be using promises. So you'd take the first
, second
and third
definition from your Promises section, and then:
async function firstSecondThird() {
let firstPromiseValue = await first();
console.log(firstPromiseValue);
let secondPromiseValue = await second();
console.log(secondPromiseValue);
third(); // not a promise, no need to await
}
firstSecondThird();
Which is the good flow control for javascript applications?
Objectively, none of them are better; but async/await
is the most readable, callbacks the most explicit (with then
code being in the middle).
What about some async library which uses methods like async.waterfall, etc..
Promises generally do everything those libraries do, and also got selected to be standardised. You may forget about those libraries unless you are maintaining old code that requires them.
By the way, is my above code is ok or not?
It seems to do what you want it to do, more or less, without obvious problems in efficiency or legibility. I'd say it's OK.
How do I convert this chained promises code with callback to async/await
Here is what you want:
var responseCallbacks = {};
bot.onText(/\/something/, async (msg) => {
var callback = responseCallbacks[msg.chat.id];
if (callback) {
delete responseCallbacks[msg.chat.id];
return callback(msg);
}
await bot.sendMessage(msg.chat.id, "something");
responseCallbacks[msg.chat.id] = async (answer) => {
var something = answer.text;
await bot.sendMessage(msg.chat.id, "something else");
responseCallbacks[msg.chat.id] = (answer) => {
var somethingElse = answer.text;
console.log(something, somethingElse);
};
};
});
Using async/await with callback functions
findOne
returns an awaitable object - so you don't need to pass a callback to it. Don't try mixing callbacks with async/await
. The only way to return the value from the callback, as a result of the constructed promise is by using resolve
(only available in the promise executor).
Instead, make it all async
- functionally similar but far cleaner.
async findForUser(userId: string | Types.ObjectId): Promise<Achievement[]> {
const user = await UserSchema.findOne({ _id: userId });
const AchievementMap: Achievement[] = [];
user.achievements?.forEach(a => {
AchievementMap.push(a);
});
return AchievementMap;
}
Related Topics
Define Global Variable with Webpack
How to Configure Cors in a Spring Boot + Spring Security Application
Asynchronous for Cycle in JavaScript
When Does Reflow Happen in a Dom Environment
Operator Precedence with JavaScript Ternary Operator
Why Is Mutating the [[Prototype]] of an Object Bad for Performance
How to Deal with Big Numbers in JavaScript
Why Doesn't a JavaScript Return Statement Work When the Return Value Is on a New Line
What Do These JavaScript Bitwise Operators Do
How to Dynamically Change Header Based on Angularjs Partial View
Check If a Variable Is of Function Type
Generic Deep Diff Between Two Objects
Check Whether Variable Is Number or String in JavaScript
How to Detect If Browser Window Is Scrolled to Bottom
Check/Uncheck Checkbox with JavaScript