In calling an async function, I am expecting it to return a JSON payload so I can extract a value from the object. However, the function only returns [object Object]
The async function was being called in a normal function, so I tried changing the parent function to an async function. This helped me because originally I was only getting a value of [object Promise]
Originally, I was attempting this:
const sendRequestToApprover = (userId, announcement, username) => {
const { title, details, channel } = announcement;
const channelName = channels.getChannelName(channel);
console.log('channelName' + channelName);
and getChannelName
looks like:
async function getChannelName(id) {
try {
return await api.get('/channels.info', {
params: {
token: botToken,
channel: id,
}
});
} catch (err) {
console.log(err);
}
}
I was able to resolve the issue of getting [object Promise]
by making the following change to sendRequestToApprover
:
async function sendRequestToApprover(userId, announcement, username) {
const { title, details, channel } = announcement;
const channelName = await channels.getChannelName(channel);
console.log('channelName' + channelName);
Note it is now an async function and I added await
to the function call.
I know the payload called by will return the following:
{
"ok": true,
"channel": {
"id": "CJSFDR83T",
"name": "general",
...
}
I can't quite figure out why I can't get to the name in this case. I've done this in other functions and this one has me stumped. channelName
is still returning [object Object]
.
When you're doing this:
console.log("channelName" + channelName);
You're calling the toString
method on channelName
, and on an object this results in [object Object]
.
console.log("Object.toString() -> " + { foo: "bar" });
You can avoid this by passing another argument to console.log
.
console.log("Object.toString() -> ", { foo: "bar" });
I feel pretty defeated after trying to figure this out this weekend.
I figured this out by assigning the API call to a variable and logging the result.
try {
const result = await api.get('/channels.info', {
params: {
token: botToken,
channel: id,
}
});
Then I tried logging result
and saw the payload! So I updated the function as so:
async function getChannelName(id) {
try {
const result = await api.get('/channels.info', {
params: {
token: botToken,
channel: id,
}
});
return result.data.channel.name
} catch (err) {
console.log(err);
}
}
Now my channelName
variable returns the channel name!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.