Javascript jQuery延迟-多个块中的执行顺序
注意Javascript jQuery延迟-多个块中的执行顺序,javascript,jquery,asynchronous,es6-promise,jquery-deferred,Javascript,Jquery,Asynchronous,Es6 Promise,Jquery Deferred,注意 这个问题只会在特定的服务器端api中出现。因此,它解决了错误的问题。我不会删除它,因为它有答案和评论 我尝试执行一些ajax请求,在每个请求完成后执行一些操作,在所有请求完成后执行一些其他操作,为此我使用以下代码: let myarr = [], myfunc = arg => myarr.push(arg); $.when( $.post(myparams).done(myfunc), $.post(otherparams).do
这个问题只会在特定的服务器端api中出现。因此,它解决了错误的问题。我不会删除它,因为它有答案和评论
我尝试执行一些ajax请求,在每个请求完成后执行一些操作,在所有请求完成后执行一些其他操作,为此我使用以下代码:
let
myarr = [],
myfunc = arg => myarr.push(arg);
$.when(
$.post(myparams).done(myfunc),
$.post(otherparams).done(myfunc),
$.post(yetanother).done(myfunc)
// it comes out with only one arg
).then(e => console.log(myarr));
但是,当执行然后块时,它通常只执行第一个操作的done
,我如何解决这个问题
如果它是重复的,我很抱歉,但老实说,我甚至不知道要搜索什么:/
评论
我还尝试创建我自己的延迟,在那里我将执行ajax并在done
块中解决它们,但这产生了相同的结果
仅使用完成
或仅使用然后
,相同。根据jQuery的文档:
.then()
]的每个参数都是具有以下结构的数组:[data,statusText,jqXHR]
意思是你可以做这样的事
$.when(
$.post(myparams),
$.post(otherparams),
$.post(yetanother)
).then((res1, res2, res3) => { //Arg for each result
myfunc(res1[0]); //Call myfunc for result 1's data
myfunc(res2[0]); //Call myfunc for result 2's data
myfunc(res3[0]); //Call myfunc for result 3's data
});
虽然也许更干净的版本可能是这样的
let
myarr=[],
myfunc=arg=>myarr.push(arg);
美元。什么时候(
$.get('https://jsonplaceholder.typicode.com/todos/1'),
$.get('https://jsonplaceholder.typicode.com/todos/2'),
$.get('https://jsonplaceholder.typicode.com/todos/3')
).then((…results)=>{//将所有结果作为数组获取
results.map(r=>r[0]).forEach(myfunc);//为每个结果的数据调用myfunc
console.log(myarr);
});代码>
永远不要使用完成
,始终使用然后
@Bergi“永远不要使用完成
”-为什么如此绝对?then
和done
的用例并不相同。如果您只希望在延迟得到解决的情况下发生回调怎么办?同样的事情也会发生,只使用done
或,然后@TylerRoper我当然要简化了。我仍然没有找到done
的用例,如果那么就不起作用了,而且done
有太多的陷阱,我建议一般避免它。@LucasNoetzold这就是你的确切代码吗?你能提供一份工作吗?是的,特别是。更好