我知道类似的问题已经问过很多次了,但是有些问题已经过时,建议使用不建议使用的解决方案,有些描述了解决方案,但不是在循环的上下文中,没有一个可以直接回答我的问题。我想知道在运行一系列异步调用的另一段代码完成之后,运行一段代码的最新最好的方法是什么。
这是我拥有的代码的一般结构:
function fetchProperty(input) {
$.ajax({
url: 'https://jsonplaceholder.typicode.com/todos/1' + input
}).done(function(resp){
return $.parseJSON(resp).title;
});
}
inputValues = [1, 2];
outputValues = [];
$.each(inputValues, function(index, value){
outputValues.push(fetchProperty(value));
});
console.log(outputValues); // will return an empty array
基本上,我希望在$.each()
内进行的所有AJAX调用完成后才执行最后一行代码。显然,我不想使用async: false
,因为它已被弃用。如何将console.log
推迟到所有其他推迟的AJAX调用完成之后,什么是最佳做法?
答案 0 :(得分:2)
请尝试使用异步等待,如下面的代码所示。 问题似乎是,提取是异步的,但控制台日志不是,因此它在提取数据之前先打印
async function fetchProperty(input) {
const resp = await $.ajax({
url: 'http://some.api/' + input + '/foobar'
});
return $.parseJSON(resp).someProperty;
}
inputValues = ['this', 'that'];
outputValues = [];
$.each(inputValues, async function(index, value){
outputValues.push(await fetchProperty(value));
});
console.log(outputValues);
答案 1 :(得分:1)
我不确定$.ajax
是否返回可能的(像Promise之类的)对象。然后,我将首先将$.ajax
转换为Promise,并使用await
关键字从函数中获取值。我使用for...of
而不是$.each
来完成此任务,因为$.each
使用callback
样式,那么很难使其与async/await
一起使用。 >
function fetchProperty(input) {
return new Promise((resolve) => { // return a Promise
$.ajax({
url: 'https://jsonplaceholder.typicode.com/todos/' + input
}).done(function (resp) {
resolve(resp.title); // resolve here
});
});
}
async function main() {
const inputValues = [1, 2];
const outputValues = [];
for (const value of inputValues) {
outputValues.push(await fetchProperty(value));
}
console.log(outputValues); // the values
}
main();