console.log after await doesnt print its content [duplicate] - javascript

This question already has answers here:
Async/Await code not being executes after await
(3 answers)
After an await call, it doesn't execute next line [closed]
(1 answer)
Closed 6 months ago.
I read about async/await, but I've a question. I know that await only works with promises, but why in the code below, the last console doesn't print at all!
async function printMe() {
console.log("First")
await new Promise (resolve => {setTimeout(() => console.log("Async!!!"), 3000)})
console.log("Last")
}
printMe()

When using Promise, you need to call the resolve method to fulfil the promise:
async function printMe() {
console.log("First")
await new Promise (resolve => {setTimeout(() => {
console.log("Async!!!")
resolve()
}, 3000)})
console.log("Last")
}
printMe()
N.B: There is also a reject method available, you can find more about it by reading the related MDN page

Related

How to avoid then when calling a async function [duplicate]

This question already has answers here:
How can I access the value of a promise?
(14 answers)
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 1 year ago.
I often read that async/await is better than .then(). I learned, to use await, I need an async function. To handle errors, I need try/catch. So I built this simple get request:
const isAvailable = async (url) => {
try {
const response = await fetch(url);
const data = await response.json();
return data;
} catch (err) {
console.error(err);
}
};
const fetchedData = isAvailable("/api");
console.log(fetchedData); // Returns: Promise {status: "pending"}
When I see this, it is somehow logical for me, but I can't really understand it.
fetch() returns a Promise, thus fetchedData is a Promise. But the try block shout return an object, thus fetchedData should be a Promise. Even when I see this, it is somehow logical for me, but I can't really understand it, either. fetchedData is a pending Promise and should be awaited as well, so I tried:
const fetchedData = await isAvailable("/api"); //SyntaxError: Unexpected identifier 'isAvailable'. Expected ';' after variable declaration.
console.log(fetchedData);
I'd say this is because I call await without being in an async function, so I ended with:
isAvailable("/api").then((fetchedData) => {
console.log(fetchedData);
});
But now I'm back to .then() what I want to avoid in my exercise.

Waiting for Promise API calls to finish [duplicate]

This question already has answers here:
How to return many Promises and wait for them all before doing other stuff
(6 answers)
Using async/await with a forEach loop
(33 answers)
Closed 1 year ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Original close reason(s) were not resolved
Okay, so I have this function that is a simple Axios request. We know that Axios will run as a promise based request so we do something like this and push all the responses into an array
let array = []
function A() {
return axios.get(url).then(r => r.data).then(r => array.push(r.forms))
}
The issue is now I need to call this function specifically 898 times.
async function main() {
await someArrayWithALotOfObjects.forEach(async (e) => {
return await A(e.url);
});
console.log(array);
}
The issue is when I run main() it console logs [], however when I change the main function to be completely hardcoded it outputs all the data correctly pushed to the array in a workable format.
async function main() {
await A(someArrayWithALotOfObjects[0].url);
await A(someArrayWithALotOfObjects[1].url);
await A(someArrayWithALotOfObjects[2].url);
await A(someArrayWithALotOfObjects[3].url);
await A(someArrayWithALotOfObjects[4].url);
await A(someArrayWithALotOfObjects[5].url);
await A(someArrayWithALotOfObjects[6].url);
await A(someArrayWithALotOfObjects[7].url);
...
console.log(array);
}
So my question is how to not hardcode because the loop does not seem to be completed before I run the console.log function.
Note: eventually I will be changing the console logging to the fs event for writing to a file if this helps in writing a better solution.
Note2: IDK how to use the new yield stuff in JavaScript yet, so if that is the solution needed forgive me.

Single async function that makes multiple fetches and returns results? [duplicate]

This question already has answers here:
Why does .json() return a promise?
(6 answers)
Closed 4 years ago.
I am attempting to write an async function that makes multiple fetches, waits for all to complete, then returns the JSON results as an array. This is what I have so far:
file1.js
const searchResults = await Api.search(searchText);
api.js
async function search(searchText) {
return util.executeFetchAll([
`/searchA/${searchText}`,
`/searchB/${searchText}`,
`/searchC/${searchText}`
]);
}
util.js
async function executeFetchAll(urls) {
const promises = urls.map(url => fetch(url));
const responses = await Promise.all(promises);
debugger;
}
When execution pauses at the debugger and I inspect responses using Chrome's dev tools, it is correctly an array of 3 Response objects, but if I inspect responses[0].json(), it weirdly returns in the console a Promise {<pending>} object.
What am I missing? I'm awaiting Promise.all, which should mean all promises resolve before my debugger line. So why is the json() method weirdly showing a Promise object in a pending state?
Thanks.
response.json() return a Promise! see: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
So you can await them with something like this:
await Promise.all(responses.map(r => r.json()));

node 8: converting a promise/callback structure to async/await [duplicate]

This question already has answers here:
How to "await" for a callback to return?
(5 answers)
Closed 5 years ago.
I've got the following code block:
new Promise((res, rej) => {
if (checkCondition()) {
res(getValue())
} else {
getValueAsync((result) => {
res(result)
})
}
}).then((value) => {
doStuff(value)
})
I'd like to convert this to use async/await, but I can't figure out how to do it. I know when you're working exclusively with promises, you replace the calls to then() with value = await ..., but How do I make this work with callbacks? Is it possible?
First of all, you have to make sure you are in an async function to begin with. Then it could be something along the lines of:
async function example() {
let value = (checkCondition() ? getValue() : await getValueAsync());
doStuff(value);
}
await example();
This, however, assumes that you can modify getValueAsync as well, to make it an async function or to make it return a Promise. Assuming getValueAsync has to take a callback, there is not that much we can do:
async function example() {
let value = (checkCondition()
? getValue()
: await new Promise(res => getValueAsync(res))
);
doStuff(value);
}
await example();
You still gain the benefit of not having to create the full Promise chain yourself. But, getValueAsync needs to be wrapped in a Promise in order to be usable with await. You should carefully consider whether this kind of a change is worth it for you. E.g. if you are in control of most of the codebase and / or most of the functions you are calling are already async / return Promises.

async/await func returning a promise instead of data [duplicate]

This question already has an answer here:
Getting value from returned promise from async function
(1 answer)
Closed 5 years ago.
I have the following function in JS which is supposed to read all the entries in a firebase database.
async function getMarket() {
let marketRef = db.ref('/market');
let snapshot = await marketRef.once('value');
return snapshot.val();
}
For some reason when I call this function it returns Promise { <state>: "pending" }. Why is this happening?
An async function returns a Promise. Chain .then() and .catch() to process the returned Promise value

Categories

Resources