This question already has answers here:
Why is my infinite loop blocking when it is in an async function? [duplicate]
(2 answers)
Closed 1 year ago.
I have a function called on a submit form
async solve(e){
const waiter = (args) => new Promise((resolve, reject) => {
resolve(this.CalculateValues(args))
})
e.preventDefault();
let V=this.state.fields;
let B =await waiter(V);
this.setState({
BrokerFees:B,
SolveState:"Solve",
});
}
as you can see in the code I have a function that returns Promise i am using await keyword inside async function still my UI freezes.
Please let me know if I am doing something wrong
I think you should use async here :
solve(e){
const waiter = async (args) => new Promise((resolve, reject) => {
resolve(this.CalculateValues(args))
})
e.preventDefault();
let V=this.state.fields;
let B =await waiter(V);
this.setState({
BrokerFees:B,
SolveState:"Solve",
});
}
Related
This question already has answers here:
Resolve promises one after another (i.e. in sequence)?
(36 answers)
Is Node.js native Promise.all processing in parallel or sequentially?
(14 answers)
Closed 6 months ago.
I asked a question that was closed due to similar questions but even after reading those and seeing that map is not Promise aware, I have tried to use await Promise.all() around my mapping.
let foo = [1,2,3];
(async() => {
await Promise.all(foo.map(x => {
return new Promise(async function(resolve) {
await setTimeout(() => {
console.log("X")
resolve()
}, 3000)
});
}))
})()
instead of sequentially getting a "X" log every 3 seconds, it's just waiting 3 seconds and then logging them all. I am not sure what I am doing wrong at this point.
You are setting all the timeouts together at once. You need to increase the timeout duration in each iteration, maybe like this:
let foo = [1,2,3];
(async() => {
await Promise.all(foo.map((x, i) => {
return new Promise(async function(resolve) {
await setTimeout(() => {
console.log("X")
resolve()
}, 3000 * (i + 1))
});
}))
})()
This question already has answers here:
Returning Promise with an async function
(2 answers)
Closed 2 years ago.
I have a function that checks if an image exists, like this:
function getImage(source) {
return new Promise((resolve, reject) => {
const img = new Image()
img.onload = () => resolve(img)
img.onerror = reject
img.src = source
}
}
Should I write the function as:
async function getImage(source) {
return new Promise((resolve, reject) => {
const img = new Image()
img.onload = () => resolve(img)
img.onerror = reject
img.src = source
}
}
Does it make a difference in this particular case? Can somebody please explain?
The code will be used like this:
async function checkImage() {
try {
const img = await getImage('path-to-image')
this.logoImg = img.src // does something with the image
}
catch(e) {
this.logoImg = 'path-to-a-different-image' // does something else if the image is broken, etc.
}
}
Never mind the "this.logoImg" part.
Many thanks in advance.
No,
async is required for functions those are using await inside it.
await is used to avoid .then
Here if getImage returns promise only so no need to use async
function getImage(source) { // This function returns promise
return new Promise((resolve, reject) => {
// ..doesn't have await..
}
}
Here async is required because usingGetImage() using await inside it
async function usingGetImage(){
const img = await getImage('my-image')
}
Hope this will answer your question :)
This question already has answers here:
How to turn this callback into a promise using async/await?
(2 answers)
Closed 3 years ago.
I have two functions that are written with promises:
const resolvedDelay = (value, ms) => new Promise(resolve => setTimeout(() => resolve(value),ms));
const rejectedDelay = (value, ms) => new Promise((resolve,reject) => setTimeout(() => reject(value),ms));
I try to rewrite them via async/await. This is my wrong attempt:
const resolvedDelay = async (value, ms) => setTimeout(() => value,ms); // I haven't reference to `resolve` here... :(
const rejectedDelay = async (value, ms) => setTimeout(() => {throw new Error(value)},ms);
How to do it right?
Usually something like this is done to convert the setTimeout into a reusable promise, which is then awaitable.
const delay = time => new Promise(res => setTimeout(res, time));
const resolvedDelay = async (value, ms) => {await delay(ms); return value;};
const rejectedDelay = async (value, ms) => {await delay(ms); throw Error(value);};
You have to have a promise first in order to do anything useful with await. And, since setTimeout() doesn't create a promise and doesn't resolve or reject a promise, you HAVE to create a promise and tie it to the setTimeout() callback just like you did in your first code block.
Your second code block just calls setTimeout() and immediately returns. Wrapping it in an async makes it return a promise, but that promise is just immediately resolved when the function returns after calling setTimeout(). So, you have to be resolving or rejecting a promise when the setTimeout() callback fires and there is no way to do that with just an async function wrapper around it.
Therefore, there's no real use for async/await in creating your two functions. Your first group of functions where you manually create a promise is the way to go here.
Of course, the caller can use await with your first set of functions just fine without change.
This is how I would do it, I don't know of a way of doing it that would make it remain as an arrow function though.
function resolvedDelay(value, ms) {
return new Promise(resolve => {
setTimeout(() => {
resolve(value);
}, ms);
});
}
function rejectedDelay(value, ms) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(value);
}, ms);
});
}
async function callFunctions() {
const resolved = await resolvedDelay();
const rejected = await rejectedDelay();
// Do whatever you want with them now
}
This question already has answers here:
Async/Await Class Constructor
(20 answers)
Can async/await be used in constructors?
(4 answers)
Closed 3 years ago.
The keyword await makes JavaScript wait until that promise settles and returns its result.
I noticed its possible to await a function
var neonlight = await neon();
Is it possible to await a class?
Example
var neonlight = await new Neon(neon_gas);
Technically .. Yes, If the constructor returns a Promise and as long as the await is inside an async function, here's an example ( might not be the best, actually it's a bad practice to have a constructor function return a Promise , but it's just to get this to work ):
class Test {
constructor() {
return new Promise((res, rej) => {
this.getData().then(({userId, title}) => {
this.userId = userId;
this.title = title;
res(this);
});
});
}
getData(){
return fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
}
greet(){
console.log('hello');
}
}
(async() => {
const x = await new Test();
console.log(x.userId, ' : ', x.title);
})();
This question already has answers here:
Difference between `return await promise` and `return promise`
(7 answers)
Closed 5 years ago.
const displaySymbols = async (symbols) => {
const sym = await Promise.all(symbols.map(s => {
// createEl return a promise
return createEl(s)
}))
return sym
}
const displaySymbols = async (symbols) => {
const sym = await Promise.all(symbols.map(async s => {
return await createEl(s)
}))
return sym
}
The results are same, without Promise.all, sym would be always a promise array, no matter createEl is await-ed or not, then is it necessary to use async function as map method?
P.S. The code is just a demo.
The second one is superflous. Its like:
Promise.resolve( new Promise() )