Answering your first question, not async
and await
do not replace
the promises
, in fact the two can coexist in the same scenario;
below async
and await
handle promises to solve the states
On the other hand in your example that you put first should look like this
async function getMain(){
let message = 'Hola Mundo'
const response = await (message)
console.log(response)
}
getMain()//aquí mando ejecutar la función
Where, as you can see after the declaration of the function with keyword async
, I do:
I assign a variable message the value of "hola mundo"
I want to print
after a constant I equal it with variable message
but indicating that it must wait for the resolution of this same with the
keyword await
later I print the value with the help of console.log()
Finally, for the function to work, I only invoke it by its name and a pair of parentheses
UPDATE
If you need to compare the same exercise but from the perspective of the explicit use of promises , I leave this example also functional
let message = new Promise(function(resolve, reject){
let saludo = 'Hola Mundo';
resolve(saludo)
})
message.then((response) => {
console.log(response)
}).catch((error) => {
console.log(error.message)
})
Where you can notice that to this day we have three states of the
promises: resolve
, pending
and reject
Resolve
: it is the moment that the code flow worked normal and the contained logic was executed
Pending
, does not exist as such an error in the code but is waiting to return the result of the promise
Rejected
: indicates that it was rejected, however unlike a trhow exception, it does not kill the code flow
With regard to the last question, if it can be the case
multiple await within others; I leave an example that I have with a
Exercise in VueJS and it's functional for me
getFotos: async function(){
let data = await(await fetch("https://api.example.com/fotos")).json()
this.datos = data
}