代码之家  ›  专栏  ›  技术社区  ›  vatsal chauhan

函数未返回API调用的结果

  •  0
  • vatsal chauhan  · 技术社区  · 2 年前

    我正在尝试创建一个翻译应用程序,使用谷歌翻译API。 密码

    const apiTranslate = (() => {
        const _API_KEY = "api-key";
        async function getTranslation(text) {
            let res = await axios.post(
                `https://translation.googleapis.com/language/translate/v2?key=${_API_KEY}`,
                { q: text, target: "de" }
            );
            let translation = res.data.data.translations[0].translatedText;
            console.log(translation);
            return translation;
        }
        return Object.assign({}, {getTranslation});
    })();
    
    let text = "hello world";
    const {getTranslation} = apiTranslate;
    const message = getTranslation(text);
    console.log(message);
    

    它返回:一个具有prototype、promiseState和promiseResult属性的promise对象。 它应该回来了:你好,沃尔特。 翻译的值是正确的,因为我把它记录在代码中。

    2 回复  |  直到 2 年前
        1
  •  1
  •   Jithil P Ponnan    2 年前

    是 啊你是对的。 getTranslation 将返回一个承诺作为 async 作用

    因此,您可以使用等待或然后从中获取返回。

    一: 在您的情况下,如果您想读取脚本主体中的数据,

    let text = "hello world";
    const {getTranslation} = apiTranslate;
    
    getTranslation(text).then(message=>{
        console.log(message);
    });
    

    两个: 或者,如果要分配给变量 message 为了进一步处理,您需要编写一个函数。

    const doTranslate = async ()=> {
        let text = "hello world";
        const {getTranslation} = apiTranslate;
        const message = await getTranslation(text);
        console.log(message);
    }
    

    三: 另一种方法声明了一个立即调用函数。

    (async () => {
        let text = "hello world";
        const { getTranslation } = apiTranslate;
        const message = await getTranslation(text);
        console.log(message);
    })();
    
        2
  •  1
  •   JEFF BRO    2 年前
    async function translateText() {
        let text = "hello world";
        const {getTranslation} = apiTranslate;
        try {
             getTranslation(text).then((res=>{
                console.log(res)
             }));
           
        } catch (error) {
            console.error("Error during translation:", error);
        }
    }