Reputation: 5561
How do I pass the the returned Promise
value to another function? I need to retrieve a parsed JSON
data and then use that response data to send to Slack channel.
My index.js
// Get the data
let getData = () => {
axios.get('https://jsonplaceholder.typicode.com/posts/1').then(res => {
const responseJSON = res.data
return responseJSON
})
.catch(err => {
console.log(`Error in getData(): ${err}`)
})
}
// Post to Slack (real-time)
let slack = () => {
axios.post('url-to-post-to', {
'text': getData().toString() // This has to be a string, but right now it's returning [object Promise]
})
.catch(err => {
console.error(`Error in SLACK: ${err.response.data}`)
})
}
Right now I'm getting [object Promise]
in Slack channel, but I need the JSON
that is returning in a form of string.
I think that I'm trying to pass a value that has not yet been resolved, but the problem is, I don't know how to pass the value after it has been resolved.
Any help is appreciated.
Upvotes: 0
Views: 1653
Reputation: 22574
You can wrap your function in async-await
.
let slack = async () => {
axios.post('url-to-post-to', {
'text': await getData().toString()
})
.catch(err => {
console.error(`Error in SLACK: ${err.response.data}`)
})
}
Upvotes: 0
Reputation: 106
When working with promises, if a promise is returned from a function you can call the then property on it, and the resolved value is passed through the then paramater. You could do.
// Get the data
let getData = () => {
return axios.get('https://jsonplaceholder.typicode.com/posts/1').then(res => {
const respondeJSON = res.data
return responseJSON
})
.catch(err => {
console.log(`Error in getData(): ${err}`)
})
}
// Post to Slack (real-time)
let slack = () => {
getData().then(data =>
axios.post('url-to-post-to', {
'text': data.toString()
})
.catch(err => {
console.error(`Error in SLACK: ${err.response.data}`)
}))
}
or
// Get the data
let getData = () => {
return axios.get('https://jsonplaceholder.typicode.com/posts/1').then(res => {
const respondeJSON = res.data
return responseJSON
})
.catch(err => {
console.log(`Error in getData(): ${err}`)
})
}
// Post to Slack (real-time)
let slack = (data) => {
axios.post('url-to-post-to', {
'text': data.toString()
})
.catch(err => {
console.error(`Error in SLACK: ${err.response.data}`)
}))
}
getData().then(slack);
Upvotes: 1
Reputation: 5838
Insert your Slack call thenabled after your first call. You need to this because as you suspect, you are doing the Slack call with the result of an unfulfilled promise.
// Get the data
let getData = () => {
axios.get('https://jsonplaceholder.typicode.com/posts/1').then(res => {
const respondeJSON = res.data;
return responseJSON;
}).then(data => {
axios.post('url-to-post-to', {
'text': data
})
.catch(err => {
console.error(`Error in SLACK: ${err.response.data}`);
});
}).catch(err => {
console.log(`Error in getData(): ${err}`)
})
};
Upvotes: 2