在发出 POST 请求之前等待来自外部 API 的数据

Wait for data from external API before making POST request

我将 IBM Watson Tone Analyzer API 与 Express.js 和 React 结合使用。我有这段代码可以向 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 的值。我的问题是,如何让 res.send(...) 运行 只有在 tone 有值之后?

我尝试将 this.Analyzer.tone(input, [callback]) 中的回调函数包装在 async/await 块中,但这并没有解决问题。任何有关如何解决此问题的想法都将受到高度赞赏。谢谢!

如果调用

let tone = new ToneAnalysis().ToneAnalyser(input); 

returns 一个承诺然后你可以做类似

tone.then(res.send.bind(res))

如果调用

let tone = new ToneAnalysis()`enter code here`.ToneAnalyser(input); 

returns 一个承诺然后你可以做类似

tone.then(res.send.bind(res))