我是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);
如果有人可以提供帮助,将不胜感激。
答案 0 :(得分:0)
听起来您的环境支持异步/等待。因此,假设task1
和task2
是async
或返回Promise
,则:
await Promise.all
等待两项任务完成。这不会强制执行任何命令,但会确保两者都已完成,然后再继续。task3
。 async function task1(input){
// has more functions that do other stuff
}
async 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
}
async function main(input1, input2, input3){
await Promise.all(
task1(input1),
task2(input2)
)
task3(input3);
}
main(input1, input2, input3);
答案 1 :(得分:0)
如果您有异步代码,则要使用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()
});
由于您说的是使用访存,因此可以使用它代替诺言,因为这会返回一个诺言。
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()
});
答案 2 :(得分:0)
由于要在任务中进行API调用,因此应将每个任务定义为一个异步函数,并等待如下:
const fetch = require('node-fetch')
async function task1(input){
console.log(input)
// API call goes here
// const response = await fetch("http://localhost:5000/endpoint")
console.log(response)
}
async function task2(input){
console.log(input)
}
async function task3(input){
console.log(input)
}
async function main(input1, input2, input3){
await task1(input1); // doesn't matter which task finishes first between 1 and 2
await task2(input2);
await task3(input3); // task 3 should not be executed until task 1 and 2 have completed.
}
main("LIONS", "TIGERS", "BEARS")
您将在以下位置看到以上结果:
LIONS
TIGERS
BEARS
,所有API调用都会依次发生。