gpt4 book ai didi

javascript - 具有不同超时时间的同步回调

转载 作者:行者123 更新时间:2023-12-02 23:11:03 25 4
gpt4 key购买 nike

我正在尝试使用回调函数进行控制台,该函数本身就是 setTimeout 函数内的回调函数。如何才能得到有序的结果?

我希望先调用 f1,然后调用 f2,最后调用 f3,而不管它们的计时器如何。

let f1 = (cb) => { 
setTimeout(() => {
cb(null, {a: 1})
},100)
}

let f2 = (cb) => {
setTimeout(() => {
cb(null, {a: 2})
},50)
}

let f3 = (cb) => {
setTimeout(() => {
cb(null, {a: 3})
},10)
}

function parallelConsole(arr, cb) {
let result = [];
arr.forEach(func => {
func((temp, val) => {
console.log(val)
result.push(val)
if(arr.length === result.length) {
cb(result)
}
})
})
}

parallelConsole([f1, f2, f3], (res) => {
console.log(res) //[{a: 3}, {a: 2}, {a: 1}]
})

预期结果:[{a: 1}, {a: 2}, {a: 3}]

实际结果:[{a: 3}, {a: 2}, {a: 1}]

最佳答案

如果您确实必须使用回调,并且这是一个与生产相关的项目,请使用 async.js一个选项?它提供了一些非常有用的功能(.each 可能就是您正在寻找的功能)。

I wish to have callback for f1 called, followed by f2 and finally f3, irrespective of their timer.

我对此有点困惑。如果超时,则在指定时间过后将调用回调。或者您是否希望以有序方式(1、2、3)console.log结果,而不管回调何时被调用?

编辑:我已经修复了你的代码,所以我认为它可以满足你的要求。来自 f1, f2, f3promise 未返回。另外,正如评论中所指出的,使用 Promise.all 可以确保在所有 Promise 完成后调用最终回调。

const f1 = (cb) => {
return new Promise ((resolve) => setTimeout(() => {
resolve(cb(null, { a: 1 }))
}, 100))
};

const f2 = (cb) => {
return new Promise ((resolve) => setTimeout(() => {
resolve(cb(null, { a: 2 }))
}, 50))
};

const f3 = (cb) => {
return new Promise ((resolve) => setTimeout(() => {
resolve(cb(null, { a: 3 }))
}, 10))
};

function parallelConsole(arr, cb) {
return Promise.all(arr)
.then((values) => {
cb(null, values);
});
}

const log = (err, data) => {
if (err) {
// TODO: handle properly
return console.log(err);
}

return data;
};

parallelConsole([f1(log), f2(log), f3(log)], (err, res) => {
console.log(res)
});

关于javascript - 具有不同超时时间的同步回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57359074/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com