Aja*_*ese 6 javascript asynchronous callback
我是 JavaScript 新手,并且已经尝试让它工作一段时间了,但没有成功。
我有一个函数(任务 3),它只能在函数完成之前执行。前面的函数(任务 1 和 2)包含更多从其他源获取数据的函数,并且它们所需的时间未知。等待函数实际上不起作用,因为任务 1 和 2 的时间可能非常快或非常慢。我尝试过进行异步/等待设置,但我一定做错了,因为它总是在任务 1 或 2 之前完成任务 3。与回调函数相同,它实际上并没有回调它,只是执行了任务 1 和 2,然后从未执行过任务3.
function task1(input){
// has more functions that do other stuff
}
function task2(input){
// has more functions that do other stuff
}
function task3(input){
// this code should only be executed after both task 1 and 2 finish
}
function main(input1, input2, input3){
task1(input1); // doesn't matter which task finishes first between 1 and 2
task2(input2);
task3(input3); // task 3 should not be executed until task 1 and 2 have completed.
}
main(input1, input2, input3);
Run Code Online (Sandbox Code Playgroud)
如果有人可以提供帮助,我们将不胜感激。
如果您有异步代码,您需要使用 Promise。Promise.all()将等待它们全部完成后再运行。
function task1() {
return new Promise(function(resolve, reject) {
console.log("task 1")
setTimeout(function() {
resolve('foo');
}, Math.random() * 2000);
})
}
function task2() {
return new Promise(function(resolve, reject) {
console.log("task 2")
setTimeout(function() {
resolve('bar');
}, Math.random() * 2000);
})
}
function task3() {
console.log("task 3")
}
Promise.all([task1(), task2()]).then(function(values) {
console.log(values);
task3()
});Run Code Online (Sandbox Code Playgroud)
既然你说你正在使用 fetch,你可以使用它而不是承诺,因为它会返回一个承诺。
function task1() {
return fetch('http://example.com/foo.json')
.then(response => response.json())
}
function task2() {
return fetch('http://example.com/bar.json')
.then(response => response.json())
}
function task3() {
console.log("task 3")
}
Promise.all([task1(), task2()]).then(function(values) {
console.log(values);
task3()
});
Run Code Online (Sandbox Code Playgroud)