Promise in JavaScript
Hello guys, sorry to disturb you all; I'm learning about promises in JS... can someone just check if my understanding is correct and what you guys can add/pinpoint on this concept please.... here is what I've understood so far:
Previously, we used to make use of callbacks to perform sequential execution but this can lead to code being really difficult to understand. Now, with the use of promise, we no longer need callbacks.
In order to use a promise, we need to create and return a promise object using the following syntax:
Say we have 4 functions and we need to execute them sequentially, we can now do what is know as method chaining, like this:
func_1.then(func_2).then(func_3); ect
Please do correct me where I'm wrong... there are things still a bit unclear in my head but I understood the concept overall
14 Replies
oh boy, you kicked the hornets' nest
no, you don't need to create a promise like that if you use asyncronous functions
ah I haven't learnt about the async and await keywords yet
that's fine
also, you don't necessarily need to return promises
for example, callbacks
you can use promises to make ajax closer to fetch
also, you can return nothing at all to use a promise
and no, that's not how you call 4 functions in sequence, necessarily
the
.then
in a promise takes a callback that is executed with the data received from the promise and/or from the last .then
by the way, if you want to call 4 functions sequentially, do this:
so for example,
say u make a req to the server to get user data. now it takes an "undefined" amount of time for the server to send a response. let's assume the server responded with 200 (Ok) and responded with user data in JSON string. in order to use that data u need to parse() the json. now that also takes time. depending on factors like how big the data is, parsing can take some amount of time and is handled asynchronously. because of not knowing how long each operation can take, in order to make sure one is ran after another, so parsing is only done ONCE the res has arrived and is ok, u can use the .then() or async await
yup, that's right
wait did i forget to turn of the ping? i hope not
sorry if i forgot
you turned it off
ok tnx
but the example you show is how people do it
is .then() used nowadays or only async and await ?
both
depends on the situation
ya
ok ok ty guys
you're welcome
promises are very complicated and very simple, at the same time