Your example is not very good because the promise returns "one" in hard. And you want to get "two".
Suppose you can pass a parameter to initPromise
function initPromise(numero) {
return new Promise(function(res,rej) {
res(numero);
})
}
let data=initPromise("dos").then(function(result) {
console.log(result); // imprime "dos";
return result;
});
As data is a promise, if the logueas is not going to print the value with which the promise is resolved. It will print Promise {<pending>}
(although in this case it prints an empty object ... probably things from the sn snippets).
If what you want is to obtain the value of the answer in a synchronous way (outside the then). This can only be done using async / await:
async function initPromise(numero) {
return new Promise(function(res, rej) {
res(numero);
})
}
async function obtenerValor() {
let data = await initPromise("dos");
console.log(data);
}
obtenerValor();
The problem is that to use await
you have to be inside a function async
that in the example is obtenerValor
.
You will have to use a transpiler (e.g. Babel) for that to work in a browser.
Addendum:
Since initPromise
declared as async
always returns a promise, it does not make sense to return a promise new Promise()
from it. In the same way, if the value returned is in itself a promise, it does not make sense to declare the function as async. In other words:
// devuelve una promesa
function retornaPromesa() {
return new Promise(...);
}
// también devuelve una promesa
async function retornaValor() {
return 1;
}
// esto es redundante
async function retornaValorDePromesa() {
return new Promise(...);
}
Now, in what case would the redundant example make sense?
The grace of declaring the function as async is that within it we can use await
. For example, to request a user's permissions to an API:
// queremos hacer algo con permisos antes de retornarlos
async function revisaPermisos() {
try {
let permisos = await axios.get('/permisos/123');
if(!permisos.usuario) {
throw new Error('No es usuario');
} else if (!permisos.activo) {
throw new Error('Es usuario pero no está activo');
}
return permisos;
} catch (err) {
throw err;
}
}
In this example, I want to handle the answer in the function instead of passing that job to the caller (since they can call it from many places). If the request to the API throws an error, and revisaPermisos
is called using revisaPermisos().then(...).catch(...)
the error will appear in the block catch
. But if the call to the API does not throw error ... and nevertheless the answer must fulfill certain conditions, I can parsear that answer and submit it to certain validations, throwing errors customized by me when they are not fulfilled .
This may not be the case given the OP question, but it is an example of when it would make sense to declare async a function that inside will call another function that returns a promise.