我正在使用带有Express.js和React的IBM Watson Tone Analyzer API . 我有这个代码,它将一些测试发送到Watson API:
// tone-analyser.js
class ToneAnalysis {
constructor() {
const params = {
username: process.env.USERNAME,
password: process.env.PASSWORD,
version_date: '2018-01-31'
}
this.Analyzer = new ToneAnalyzerV3(params);
}
ToneAnalyser(input) {
let tones = this.Analyzer.tone(input, (err, tone) => {
if (err) console.log(err.message)
let voiceTone = tone.document_tone.tones[0].tone_id;
console.log(voiceTone) // Logs the right value on Node.js console
return voiceTone;
});
return tones;
}
}
module.exports = ToneAnalysis;
然后我在我的Express后端使用它,如下所示:
// server.js
const ToneAnalysis = require('./api/tone-analyser');
const app = express();
const input = {
tone_input: 'I am happy',
content_type: 'text/plain'
}
app.get('/api/tone', (req, res) => {
let tone = new ToneAnalysis().ToneAnalyser(input);
return res.send({
tone: tone
});
});
我在这里从React进行API调用:
// App.js
componentDidMount() {
this.callApi()
.then(res => {
console.log(res.tone); // Logs the wrong value on Chrome console
})
.catch(err => console.log(err));
}
callApi = async () => {
const response = await fetch('/api/tone');
const body = await response.json();
if (response.status !== 200) throw new Error(body.message);
console.log(body);
return body;
};
我希望 res.tone
的值是 string
,显示从音调分析功能( new ToneAnalysis().ToneAnalyser(input);
)获得的音调 . 相反,我得到了
{
uri: {...},method: "POST", headers: {...}}
headers: {...},
uri: {...},
__proto__: Object
}
我认为这是因为在 tone
之前运行的 res.send(...)
具有来自API的值 . 我的问题是,如何在 tone
有值后才能运行 res.send(...)
?
我尝试在 async/await
块中的 this.Analyzer.tone(input, [callback])
中包装回调函数,但这并没有解决问题 . 任何关于如何解决这个问题的想法将受到高度赞赏 . 谢谢!
1 回答
如果打电话给
返回一个承诺然后你可以做一些事情