我需要使用延迟调用外部服务器来处理对象数组,将所有结果收集到数组中并进行后处理。示例在这里:
(async () => {
const serverOperation = () => new Promise(resolve => setTimeout(() => resolve(), 2000));
const myOtherFunction = results => console.log('results', results);
const objectsArray = [{}, {}, {}];
const results = [];
const myFunc = async arr => {
const el = arr.shift();
if (!el) {
// finish of calling recursive function
return;
}
// some big server operation
const result = await serverOperation();
results.push(result);
// need to wait for some time
setTimeout(async () => {
console.log(Date.now());
await myFunc(arr);
}, 3000);
};
await myFunc(objectsArray);
await myOtherFunction(results); // <= postprocessing results
})();
问题是:在获得所有结果之前,函数myOtherFunction
已被调用。
我的问题是:如何对所有处理后的结果进行后处理?
答案 0 :(得分:0)
您可以使用超时承诺而不是setTimeout
来延迟函数的执行。
代码的问题在于,即使将async
函数传递给setTimeout
,它也不会停止当前函数的执行。 setTimeout
只会将任务移至微任务队列并执行传递给它的函数。但这不会导致父函数停止,因为传递给setTimeout
的函数不会立即调用-稍后会在不同的时间,不同的位置调用它。
(async () => {
const serverOperation = () => new Promise(resolve => setTimeout(() => resolve('server op'), 2000));
const myOtherFunction = results => console.log('results', results);
const objectsArray = [{}, {}, {}];
const results = [];
// used for delaying operations
const timeoutPromise = () => new Promise(resolve => setTimeout(() => resolve(), 3000));
const myFunc = async arr => {
const el = arr.shift();
if (!el) {
// finish of calling recursive function
return;
}
// some big server operation
const result = await serverOperation();
results.push(result);
// need to wait for some time
await timeoutPromise();
console.log(Date.now());
await myFunc(arr);
};
await myFunc(objectsArray);
await myOtherFunction(results); // <= postprocessing results
})();