Turn callback to promise and using of `await` [closed] - javascript

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I've found this sample snippets in this article :
<script>
async function get_data() { // async function
await $.get('https://url.com/one')
await $.get('https://url.com/two')
let res = await $.get('https://url.com/three')
console.log(res)
}
</script>
Which is the promised version of :
<script>
function get_data() {
$.get('https://url.com/one', () => {
$.get('https://url.com/two', () => {
$.get('https://url.com/three', (res) => {
console.log(res)
})
})
})
}
</script>
My question being, in the promised version, can we turn await $.get('https://url.com/one') into await $.get('https://url.com/one') as it is the first promise?
If yes, why would either one of both be considered as best practice?
Thank you in advance

If you want the call to url.com/two to run after url.com/one is done, you have to await the promise returned.. However, if you want all of them to run at the same same time, you can remove the await, and pass the 2 promises into a Promise.all([promise1,promise2, promise3]) which you can await

If you remove the await, it doesn't wait for the resolve or reject response from the promise.
What it does is to skip the expression in thread and continues to fetch the second response.
The first snippet is the best practice because you will get the callback hell for your code. Think about the page where you need to send 20 requests and think about callbacks. No-one can understand what request is sent from where. So with Promises, you can just wait or skip the task (if you skip, it will run in the background). So hierarchy on code structure doesn't change. Another problem is when you need to return the response to the variable. You need to put such a structure.
<script>
function get_data() {
let res = $.get('https://url.com/one', () => {
return $.get('https://url.com/two', () => {
return $.get('https://url.com/three', (res) => {
console.log(res)
return res;
})
})
})
}
</script>

Related

Is it anti-pattern to run asynchronous callbacks in catch blocks? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
Is it an anti-pattern to run asynchronous callbacks in error catching like this?
await something()
.catch(async (err) => {
console.error(err);
await otherStuff();
});
If your intent is to have that whole expression there never reject - that is, to avoid the need for
try {
await something()
.catch(async (err) => {
// ...
} catch(e) {
// handle
}
Then what you're doing right now isn't safe if there's any chance of the otherStuff call rejecting. If otherStuff might reject, then you should make sure to catch possible errors it throws, eg
await something()
.catch(async (err) => {
console.error(err);
await otherStuff();
})
.catch(handleOtherStuffErrors)
Though having an async function with only a single await isn't that useful - consider instead just returning the Promise:
await something()
.catch((err) => {
console.error(err);
return otherStuff();
})
.catch(handleOtherStuffErrors)
Chaining catches like that is pretty odd, but it's not impossible that that's what one's logic requires, so don't make a blanket statement about whether it's inherently bad.
The way you do it is. In a promise you should return the promise instead of making the callback async and awaiting it.
I don't think it is since you can call .then behind the catch. Sometimes an throw just goes into a diffrent branch of operations but at the end its preference.
await something()
.catch((err) => {
console.error(err);
return otherStuff();
}).then(res => {
// work with data
});

Are there any disadvantages or side-effects to writing all async code in IIFEs? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
I've become enamored with the async/await syntax for consuming promises since it looks and acts like synchronous code.
Although I see most examples of async/await with named functions, I find that I always write async/await code now in IIFEs, since it is mere syntactic sugar anyway, like this:
btnInOrderElem.onclick = () => {
(async () => {
contentElem.innerHTML = '';
loaderAreaElem.style.display = 'inline';
addLi(await loader.getData());
addLi(await loader.getData());
addLi(await loader.getData());
loaderAreaElem.style.display = 'none';
})();
}
Is there anything I'm missing with this practice? Are there disadvantages to doing this at some point? Is there any reason to create named functions in order to run async/await code?
In your specific example, there's really no difference between any of these:
btnInOrderElem.onclick = async () => { ... }
btnInOrderElem.onclick = () => {
(async () => { ... })()
}
async function onClickHandler() { ... }
btnInOrderElem.onclick = onClickHandler
When you define a function as async, it means Javascript will automatically cause that function to always return a promise, that resolves when it's inner tasks are completed. While the function definitions are different in the above code snippets (some would return a promise while others return undefined), the actual program will behave the same, because the browser ignores whatever is returned from the event handler (usually).
If, however, you were writing a utility function like this:
function getUser() {
(async () => { ... })()
}
// or
async function getUser() { ... }
There is an important difference. The second function will return a promise, so you can await that promise and get the resulting value. The first function will dispatch an async action then return undefined. You can't get a resulting value out of the first, nor can you await it.
Here's an exercise for you.
const wait = ms => new Promise(resolve => setTimeout(resolve, ms))
async function waitThenLog(ms, message) {
await wait(ms)
console.log(message)
}
;(async function main() {
await waitThenLog(500, 'Hello World!')
console.log('done')
})()
Above I have a simple program. It'll wait 500ms then log a message, then logs "done". Try changing it so that the waitThenLog() function uses your IIFE idea and see if you can get it to work. You'll find that you will run into some fundamental problems.

How do I consume an asynchronous response twice [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I'm looking for best nodeJS practice to consume the result of an asynchronous operation in two places.
I currently have the following pseudo-code
async function doSomething() {
const something = await fetchSomething();
console.log("something", something); // (A)
}
function fetchSomething() {
const promise = fetch("http://example.com/something");
/* new code to update something will live here (B) */
return promise;
}
So far so good
I now need to do make a change to update something within fetchSomething() at the line new code will live here. The new code will be something like something.timestamp = new Date();
How can I access something within fetchSomething() and be sure that the update I make to something at (B) occurs before I log something at (A).
Just convert your fetchSomething to also be async:
async function doSomething() {
const something = await fetchSomething();
console.log("something", something); // (A)
}
async function fetchSomething() {
const something = await fetch("http://example.com/something");
/* new code to update something will live here (B) */
something.someOtherThing = 'updated something!';
return something;
}
Every async function returns a Promise so you can just await it again.

Which is better Await Vs Then for NodeJs Promise? and How Await works [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
Hi I just started nodejs, I read some articles for async functions. There are some something really confused me, I hope to get some explanation or recommended materials here.
I know in async function, we can resolve a promise using then, also we can use 'await' to wait for promise resolved. Which is better? or are they same mechanism?
Actually, I use multiple await in my nodejs async function, for my understanding, await will stop the script and wait. This is sound like a synchronous function, right? So why do we need await? Is this a good way to do coding in Node?
I call these async functions in angularJS(using promise.then()) to get result. How does it works? I mean, what will I happened when angular call node function, how do them communicate?
If any unclear please comment.
Thank you so much
An async function, always return a pending Promise that will be resolved with the value returned by the function (so the function runs asynchronously)
Using await, the current function is suspended until the promise associated with the await is resolved (so the javascript below an await is transformed to a then() of the awaited promise)
Using then(), you stay in the function after declaring the promise, meaning that you can start multiple promises in parallel.
await is interesting because it simplifies the code when you have to wait for the result before continuing the function, like using a then for rest of the function.
Because await suspends the code, everything below an await is deferred, including any new promise.
So if you want to start all the promises in backgound, you must declare and store them into variables before using any await, like this:
var p1 = new Promise(...)
var p2 = new Promise(...)
try {
let r1 = await p1;
let r2 = await p2;
} catch (e) {}

How can we use promise in node.js packages [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
When we write a module for node.js, we use callback functions. I learned promises in javascript and I want to use in node.js module. Can we use promises instead of callback functions ? if we can, how ?
note : via function in node module file ( you know exports.some_func ) , we do somethings and we can send back informations with callback . Can we use promise instead of that callback ?
Can we use promise instead of that callback ?
Yes, rather than accepting a callback in your exported function, you can just return a promise and make sure that promise is resolved/rejected with the proper value/reason when the async operation is done.
Here's an example:
Imagine you have a module interface for reading a file, then you can have that interface return a promise like this:
// myFileModule.js
const fs = require('fs');
module.exports.getFile = function(filename, options) {
return new Promise(function(resolve, reject) {
fs.readFile(filename, options, function(err, data) {
if (err) return reject(err);
resolve(data);
});
});
}
The caller would then use it like this:
const myFiles = require('myFileModule.js');
myFiles.getFile('temp.txt').then(function(data) {
// process data here
}, function(err) {
// got an error here
});

Categories

Resources