如何将返回的 Promise
值传递给另一个函数?我需要检索已解析的 JSON
数据,然后使用该响应数据发送到 Slack channel 。
我的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}`)
})
}
现在我在 Slack channel 中收到 [object Promise]
,但我需要以字符串形式返回的 JSON
。
我认为我正在尝试传递一个尚未解决的值,但问题是,我不知道如何在解决后传递该值。
感谢任何帮助。
最佳答案
在第一次通话后插入您的 Slack 通话thenabled。您需要这样做,因为正如您怀疑的那样,您正在执行 Slack 调用,结果是未履行的 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}`)
})
};
关于json - 如何将已解决的 promise 值传递给另一个函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48724057/