Node js谷歌翻译API,不带回调

问题描述 投票:1回答:1

import React from 'react';
import './Message.css';
import ReactEmoji from 'react-emoji';

var api = "**************";
var googleTranslate = require('google-translate')(api);
const Message = ({ message: { text, user }, name ,language}) => {
  let isSentByCurrentUser = false;

  const trimmedName = name.trim().toLowerCase();
  if(user === trimmedName) {
    isSentByCurrentUser = true;
  }

  var txt = googleTranslate.translate(text, 'es', function(err, translation) {
    console.log("Spanish :>",translation.translatedText);
  });	

  return (
    isSentByCurrentUser
      ? (
        <div className="messageContainer justifyEnd">
          <p className="sentText pr-10">{trimmedName}</p>
          <div className="messageBox backgroundBlue">
            <p className="messageText colorWhite">{ReactEmoji.emojify(text)}</p>
          </div>
        </div>
        )
        : (
          <div className="messageContainer justifyStart">
            <div className="messageBox backgroundLight">
              <p className="messageText colorDark">{ReactEmoji.emojify(txt)}</p>
            </div>
            <p className="sentText pl-10 ">{user}</p>
          </div>
        )
  );
}
export default Message;

嗨。我正在尝试将“文本”翻译成西班牙文,并将其放入var“ txt”中,然后将其返回。但是我不知道如何避免goole translation api的回调。有什么想法吗?

javascript node.js callback google-translation-api
1个回答
0
投票

async一起使用await / Promise


async function getTranslation(text){
    return new Promise((resolve, reject) => {
        googleTranslate.translate(text, 'es', function(err, translation) {
            if(err){
                reject(err);
            }else{
                resolve(translation);
            }
        });
    });
}

比起您可以在异步函数中使用await

async function test(){
    let result = await getTranslation('<text to translate>');
    console.log(result);
}
© www.soinside.com 2019 - 2024. All rights reserved.