help with asynchronous javascript

let promise = new Promise(function(resolve, reject){
setTimeout(()=> resolve("done"), 1500)
})
console.log(promise)
});
let promise = new Promise(function(resolve, reject){
setTimeout(()=> resolve("done"), 1500)
})
console.log(promise)
});
why when i run this and check the console, and click the promise object before 1.5second, it stays pending forever, but if i click the promise object after 1.5 seconds, it fulfilled
26 Replies
13eck
13eck2mo ago
That's because you're logging the value of promise at that moment in time. console.log isn't real-time. But when you click on it it forces an internal refresh of the Promise object and shows the fulfilled state. What you should be doing instead is this:
let promise = new Promise((resolve, reject) => {
setTimeout(() => resolve("done"), 1500);
});
promise.then(console.log);
let promise = new Promise((resolve, reject) => {
setTimeout(() => resolve("done"), 1500);
});
promise.then(console.log);
That way, after the second and a half, it'll log done to the console (the returned value of your resolver). Note that promise.then(console.log); is the point-free version of promise.then( (value) => console.log(value));. If you're calling a function within a function and passing the value to the inner function you can remove the outer and inner () and it'll call the function directly.
bfmv
bfmvOP2mo ago
ohhhh
Choo♚𝕂𝕚𝕟𝕘
Console logs of objects can be confusing because you can actually get two values from a single log. The value at the time that the log was run is the value you get if you don't click on the triangle. The value that you get when you click the triangle is the current value at the time when you click on it.
bfmv
bfmvOP2mo ago
ohhh when javascript.info says: "Methods Promise.resolve and Promise.reject are rarely needed in modern code, because async/await syntax (we’ll cover it a bit later) makes them somewhat obsolete. We cover them here for completeness and for those who can’t use async/await for some reason." do they mean
let promise = new Promise(function(resolve, reject) {
resolve("done");

reject(new Error("…")); // ignored
});
}
let promise = new Promise(function(resolve, reject) {
resolve("done");

reject(new Error("…")); // ignored
});
}
is also outdated? cuz they used this in the majority of like 4 chapters of the promises section and now theyre saying its outdated😭
13eck
13eck2mo ago
It’s not outdated, it’s more that most JS devs don’t understand promises so the async/await syntax was designed to make it look more like what they expect code to look like. Both can and are used in production all over the place. It’s more of a stylistic choice than one being outdated.
ἔρως
ἔρως2mo ago
the use of async/await also reduce the amount of callback hell if you need to do 2+ async operations in a row, then the async/await can be vastly superior but you need to be in an async function to use await
13eck
13eck2mo ago
That’s partially a skill issue. You can reduce callback hell by using declared functions instead of inlining everything.
ἔρως
ἔρως2mo ago
that's true, but the equivalent of this:
let x = await fetch(...);
let y = await xyz(x);
let x = await fetch(...);
let y = await xyz(x);
is something like this:
function xyz(x) {
// something
}

fetch(...).then(x => xyz(x));
function xyz(x) {
// something
}

fetch(...).then(x => xyz(x));
not too bad, right? but what about return async fetch(...)?
13eck
13eck2mo ago
😒
bfmv
bfmvOP2mo ago
but in javascript.info it was said that to avoid callback hell we use promises
ἔρως
ἔρως2mo ago
a promise receives a callback
13eck
13eck2mo ago
Using callbacks is inevitable. Callback hell is when you have so many callbacks you can't tell left from right.
ἔρως
ἔρως2mo ago
yup, very common with dogwater apis written before promises existed, like indexeddb (which is why people use wrappers on top of it, so you can use promises or async/await with it)
13eck
13eck2mo ago
Callback hell is when you have so many callbacks you're indented like 8 or 9 times (or more 🙀 ) and can't remember what context you're in. Promises help to flatten that by passing data from one .then() method to another. You still use a callback function in each .then() (even if an anonymous one), however, since that's how JS works 🤷
ἔρως
ἔρως2mo ago
the async/await is syntactic sugar for it all, and makes a promise in the background anyways, but the code may look neater i would call it "hell" if you are more than 2 deep
13eck
13eck2mo ago
Yeah, the 8+ was a bit of exaggeration. I concur that 3+ is hell
ἔρως
ἔρως2mo ago
depending on the api, it might be possible to go that deep
13eck
13eck2mo ago
Here's a great article from 20019 from Zell Liew about it, showcasing what callback hell is, how to avoid it with promises, as well as async/await: https://www.freecodecamp.org/news/how-to-deal-with-nested-callbacks-and-avoid-callback-hell-1bc8dc4a2012/
freeCodeCamp.org
How to deal with nested callbacks and avoid “callback hell”
JavaScript is a strange language. Once in a while, you have to deal with a callback that’s in another callback that’s in yet another callback. People affectionately call this pattern the callback hell. It kinda looks like this: firstFunction(args, fu...
13eck
13eck2mo ago
The example given is making a burger :p
ἔρως
ἔρως2mo ago
that is actually a perfectly interesting way to put it
bfmv
bfmvOP5w ago
async function getApi(){
const url = "https://api.weatherapi.com/v1/current.json?key=435d2c5ad26448cba8c150119251907&q=London&aqi=no"

let response = await fetch(url)
let json = await response.json
console.log(json)
}

getApi()
async function getApi(){
const url = "https://api.weatherapi.com/v1/current.json?key=435d2c5ad26448cba8c150119251907&q=London&aqi=no"

let response = await fetch(url)
let json = await response.json
console.log(json)
}

getApi()
the console.log result is just
ƒ json() { [native code] }
ƒ json() { [native code] }
why i didnt receive the data
13eck
13eck5w ago
That’s because you need to await response.json(). It’s a function. That’s what the console is telling you
bfmv
bfmvOP5w ago
ohhhhhhhhh and i was cursing the website i used for the api for like 3 hours😭
ἔρως
ἔρως5w ago
no, you just didn't execute the function
13eck
13eck4w ago
One thing you forgot to do was check for errors:
async function getApi(){
const url = "https://api.weatherapi.com/v1/current.json?key=435d2c5ad26448cba8c150119251907&q=London&aqi=no";

const response = await fetch(url);
if (!response.ok) {
throw new Error(response.statusText);
}
const json = await response.json();
console.log(json);
}

getApi();
async function getApi(){
const url = "https://api.weatherapi.com/v1/current.json?key=435d2c5ad26448cba8c150119251907&q=London&aqi=no";

const response = await fetch(url);
if (!response.ok) {
throw new Error(response.statusText);
}
const json = await response.json();
console.log(json);
}

getApi();
Or using promise chaining:
fetch("https://api.weatherapi.com/v1/current.json?key=435d2c5ad26448cba8c150119251907&q=London&aqi=no")
.then((res) => res.ok ? res : throw new Error(res.statusText))
.then((res) => res.json())
.then(consol.log)
.catch(console.error);
fetch("https://api.weatherapi.com/v1/current.json?key=435d2c5ad26448cba8c150119251907&q=London&aqi=no")
.then((res) => res.ok ? res : throw new Error(res.statusText))
.then((res) => res.json())
.then(consol.log)
.catch(console.error);
And, of course, the .then() callbacks can be named functions, too:
const checkOk = res => res.ok ? res : throw new Error(res.statusText);
const getJSONfromRes = (res) => res.json();
fetch("https://api.weatherapi.com/v1/current.json?key=435d2c5ad26448cba8c150119251907&q=London&aqi=no")
.then(checkOk)
.then(getJSONfromRes)
.then(consol.log)
.catch(console.error);
const checkOk = res => res.ok ? res : throw new Error(res.statusText);
const getJSONfromRes = (res) => res.json();
fetch("https://api.weatherapi.com/v1/current.json?key=435d2c5ad26448cba8c150119251907&q=London&aqi=no")
.then(checkOk)
.then(getJSONfromRes)
.then(consol.log)
.catch(console.error);
And now it almost reads like a sentence! "Fet from URL. Then check if it's ok. Then get JSON from the response. Then log it. Else log the error.
bfmv
bfmvOP4w ago
yeah i did it in the updated code

Did you find this page helpful?