我都试过了.我想从服务器获取循环中的一些数据,并按照运行for循环的顺序将Response添加到数组中.

我认为答案是递归的,但try 了几次,都失败了.

我正在使用AXIOS:

let currentPhraseWordAssign = [];

function addPartOfSpeechAndWordPhrasesToFullScript () {
    assignPartOfSpeechAndAddToPhraseArray(["phrase", "run"]).then(() => {console.log(currentPhraseWordAssign)});
}


async function assignPartOfSpeechAndAddToPhraseArray (phrase) {
    if(currentPhraseWordAssign.length >= phrase.length) {
        console.log(currentPhraseWordAssign);
        currentPhraseWordAssign = [];
        return;
    }
    let word = phrase[currentPhraseWordAssign.length];
    axios({
        method: 'get',
        url: `http://localhost:9200/english_minus_verbs/_search`,
        headers: {
            'Content-Type': 'application/json'
        },
        data: {
            _source: ["part_of_speech"],
            query: {
                term: {
                    word: word,
                }
            }
        }
    }).then((r) => {
        try {
            currentPhraseWordAssign.push({word: word, partOfSpeech: r.data.hits.hits[0]._source.part_of_speech});
        }catch (e) {
            currentPhraseWordAssign.push({word: word, partOfSpeech: 'verb'});
        }
    }).then(()=>{
        assignPartOfSpeechAndAddToPhraseArray(phrase);
    });
}

也许那个代码完全错了,反正就像我第七次写它...我try 了promise 、异步/等待、同步和现在的递归...

推荐答案

可以按如下顺序(一个接一个)运行axios调用:

async function lookupWords(arrayOfWords) {
    let currentPhraseWordAssign = [];
    for (let word of arrayOfWords) {
        const data = await axios({
            method: 'get',
            url: `http://localhost:9200/english_minus_verbs/_search`,
            headers: {
                'Content-Type': 'application/json'
            },
            data: {
                _source: ["part_of_speech"],
                query: {
                    term: {
                        word: word,
                    }
                }
            }
        });
        currentPhraseWordAssign.push({word: word, partOfSpeech: r.data.hits.hits[0]._source.part_of_speech});        
    }
    return currentPhraseWordAssign;
}

或者,您可以并行运行它们并按顺序收集结果:

function lookupWords(arrayOfWords) {
    return Promise.all(arrayOfWords.map(word => {
        return axios({
            method: 'get',
            url: `http://localhost:9200/english_minus_verbs/_search`,
            headers: {
                'Content-Type': 'application/json'
            },
            data: {
                _source: ["part_of_speech"],
                query: {
                    term: {
                        word: word,
                    }
                }
            }
        }).then(r => {
            return {word: word, partOfSpeech: r.data.hits.hits[0]._source.part_of_speech};
        });
    }));
}

如果并行运行它们(可能会更快完成),则必须确保目标服务器将接受多个同时请求,因为您的数组很长.某些服务器将限制或拒绝太多的同时请求.要在同时有N个请求在运行的情况下半并行运行(如何并行处理一个大型数组而不同时有太多请求),可以使用mapConcurrent()之类的值来控制执行.

Javascript相关问答推荐

如何使用JavaScript向html元素添加样式

使用Apps Script缩短谷歌表中的URL?

React对话框模式在用户单击预期按钮之前出现

如何使用Echart 5.5.0创建箱形图

node TS:JWT令牌签名以验证客户端和后台问题之间的身份验证

如何在Connect 4游戏中 for each 玩家使用位板寻找7形状?

使用javascript将Plotly Expandable Sparkline转换为HighCharter Plot在bslib卡中

从WooCommerce Checkout Country字段重新排序国家,保持国家同步

当点击注册页面上的注册按钮时,邮箱重复

MathJax可以导入本地HTML文档使用的JS文件吗?

阿波罗返回的数据错误,但在网络判断器中是正确的

如何从网站www.example.com获取表与Cheerio谷歌应用程序脚本

您能在卸载程序(QtInsteller框架)上添加WizardPage吗?

我怎么在JS里连续加2个骰子的和呢?

如何使用JavaScript拆分带空格的单词

在css中放置所需 colored颜色 以填充图像的透明区域

Reaction组件在本应被设置隐藏时仍显示

如何 for each 输入动态设置输入变更值

如何在和IF语句中使用||和&;&;?

使用createBrowserRoutVS BrowserRouter的Reaction路由