我有这段代码正在从API中搜索词汇表newvocabpasted
的同义词。
返回的每个列表都添加到数组obj
中。 (我最终得到一个数组数组-这就是我想要的)。
问题是当我在不同时间运行代码时,请求中的data
会以不同的顺序返回。这导致出现一个问题,该问题将告诉我搜索的词汇列表的成员具有不正确的同义词。
我认为这是由于getJSON调用的异步特性-因此尝试了async / await方法。但是-我仍然有问题。
为什么函数中的代码没有“等待”?并且-如果可以-并且该功能的其余部分正在运行...我该如何解决我的问题?
p = 0;
for (m of newvocabpasted) {
console.log("Loop:"+p);
//search online for list of synoynyms of newvocabpasted[p]
q1 = "https://words.bighugelabs.com/api/1/754ccc845dff7cb4459e3b40365609fb/",
q2 = "/",
q3 = "json";
query = q1+m+q2+q3;
console.log("Looking for:"+m);
$.getJSON(query,
async function(data) {
//put results in elements of an array called obj
console.log(p);
obj[p] = await data;
console.log(p);
console.log(obj[p]);
await p++;
});
}
答案 0 :(得分:1)
函数中的代码为什么不“等待”?
您必须等待承诺,而不是任意值。 data
和p
都不是承诺。
$.getJSON
返回一个承诺。这就是您await
所需要的。
答案 1 :(得分:1)
我写了一个使用Promise的示例,以便您可以了解正在发生的事情。
// We use "async" in a function every time we are going to deal with promises.
$(async function () {
const url = 'https://words.bighugelabs.com/api/1/754ccc845dff7cb4459e3b40365609fb/';
const words = ['go','stay','run'];
for (let w of words) {
// Since $.get returns a promise, we use await to catch the result from it once the request is fullfilled.
const res = await $.get(url + w);
// Split all the results in order to create an array.
const arrResults = res.split('\n');
// Promises get fullfilled in the same order as requested.
console.log(w, arrResults.length);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
我希望这会有所帮助。