Reputation: 847
I have a promise function for example getName(code)
so we have:
getName(code)
.then(...)
.catch(...);
We want to define a function to return the result name to it and do something with it.
How can we relate the defined function and method call?
For example:
async function name(code) {
getName(code)
.then(...)
.catch(...);
return ???
}
for (let i = 0; i <= 10; i++) {
let x = name(i);
// Do something with x, for example:
alert(x);
}
P.S: I know that the result is accessible inside .then
body, but I want to access it inside the name
function scope and return it from the function.
Upvotes: 1
Views: 950
Reputation: 707696
I was asked what I would suggest.
You have an asynchronous result. That means your function returns long before the asynchronous result is available. Therefore, you cannot return the asynchronous result directly.
The usual two options for communicating back an asynchronous result are a callback or returning a promise. In either case, the caller of the function has to use the asynchronous result in the specific manner in which it's returned, not as a direct return value.
In your case, you are already using promises so what makes sense is to just return the promise you already have:
function name() {
return getName(code).then(...);
}
There is no advantage to using an async
function here or await
as you just have a single asynchronous operation that's already got a promise. Just return that promise. We don't put a .catch()
handler here because there's no specific error processing required at this level - we want the rejected promise to be seen by the caller as is.
Then, to use this function which returns a promise, you can either use .then()
on it:
name().then(result => {
// use the result in here
console.log(result);
}).catch(err => {
console.log(err);
});
or you can use await
:
async function someOtherFunc() {
try {
let result = await name();
// do something with result here
} catch(e) {
console.log(e);
}
}
I know that the result is accessible inside .then body, but I want to access it inside the name function scope and return it from the function.
You can't access it outside the .then()
handler and you can't return it directly from the function. That's a limitation of asynchronous operations in Javascript. The function itself returns BEFORE the asynchronous callback has even been called so the asynchronous result isn't available at the time the function returns. This is what promises are for. You return the promise and you set it up so the asynchronous result is the resolved value of the promise. The caller then uses that returned promise to register an interest in the eventual resolved value (or reject error).
Upvotes: 2
Reputation: 10960
Use await
async function name(code) {
try {
const name = await getName(code);
// Do something here
return name;
} catch (e) {
console.log('[ERROR]', e);
}
}
Remember, In-order to use await
, the code should be enclosed within an async
function.
Upvotes: 4