Javascript承诺:遍历所有对象键数组,然后解析 [英] Javascript Promises: Iterate over all object keys arrays and then resolve

查看:72
本文介绍了Javascript承诺:遍历所有对象键数组,然后解析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个JS对象:

let setOfWords = {
    "nouns": [
        "work",
        "construction",
        "industry"
    ],
    "verbs": [
        "work"
    ],
}

我正在使用谷歌翻译API,该API调用REST资源,因此我需要等待每次翻译的响应,然后使用翻译后的单词解析相同的对象结构.

I'm using the google translate API which calls a REST resource, so I need to wait for the response of each translation and then resolve the same object structure but with the translated words.

function translateByCategory(){
    let translatedObj = {};
    return new Promise(function(resolve, reject){

        Object.keys(obj).forEach(function(category){
            if (translatedObj[category] == undefined) {
                translatedObj[category] = [];
            }
            setOfWords.forEach(function(word){
                google.translate(word, 'es', 'en').then(function(translation){
                    translatedObj[category].push(translation.translatedText);
                });
            });

            // return the translatedObj until all of the categories are translated
            resolve(translatedObj);
        });
    });
}

推荐答案

您可以使用Promise.all()等待所有的诺言兑现(或第一次拒绝)

You can use Promise.all() to wait for all promise fulfillments (or first rejection)

var translateRequests = [];

Object.keys(setOfWords).forEach(function(category){
        setOfWords[category].forEach(function(word){
            translateRequests.push(google.translate(word, 'es', 'en'));
        });
    });
});

Promise.all(translateRequests).then(function(translateResults){
    //do something with all the results
});

在此处查看文档: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

这篇关于Javascript承诺:遍历所有对象键数组,然后解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆