业务场景描述
1.模拟接口:循环创建多个promise方法,第一个返回1,第二个返回2
2.必须按顺序依次调用,调用第一个Promise返回1后,再调用第二个Promise返回2,依此类推…()
async await结合for of
// 动态创建多个 Promise 方法
function createFetchPromise(value) {
return new Promise((resolve) => {
setTimeout(() => {
console.log(`Promise with value ${value} resolved`);
resolve(value);
}, 1000); // 模拟1秒延迟
});
}
async function fetchSequentially() {
const values = [1, 2, 3, 4, 5]; // 模拟多个接口参数
// 依次处理每个接口调用
for (const value of values) {
const result = await createFetchPromise(value); // 等待当前 Promise 完成
console.log('Result:', result);
}
}
fetchSequentially();
createFetchPromise(value)
是一个动态创建 Promise
的函数,每个 Promise
在 1 秒后返回相应的 value
。for...of
循环通过 await
等待每个 Promise
完成。
reduce
// 创建 Promise 函数
function fetchData(index) {
return new Promise((resolve) => {
setTimeout(() => {
console.log(`Promise ${index} resolved`);
resolve(index);
}, 1000); // 模拟1秒延迟
});
}
const tasks = [1, 2, 3, 4, 5];
// 使用 reduce 依次调用
tasks.reduce((previousPromise, nextValue) => {
return previousPromise.then(() => {
return fetchData(nextValue);
});
}, Promise.resolve());
递归
// 创建 Promise 函数
function fetchData(index) {
return new Promise((resolve) => {
setTimeout(() => {
console.log(`Promise ${index} resolved`);
resolve(index);
}, 1000); // 模拟1秒延迟
});
}
const tasks = [1, 2, 3, 4, 5];
//第一种递归终止条件写法
async function getApi(list = [], index = 0) {
if (index >= list.length) return;
await fetchData(index);
index++;
getApi(list, index);
}
//第二种递归终止条件写法
// async function getApi(list = [], index = 0) {
// if (!list[index]) return;
// await fetchData(index);
// index++;
// getApi(list, index);
// }
getApi(tasks);
这里提供了两种递归终止条件,第一种写法 (index >= list.length
) 通常是更好的选择,适用于大多数标准数组遍历情况。它逻辑更明确和健壮,对任何 list
都有效,包括空数组。第二种写法 (!list[index]
) 在你明确希望 null
或 undefined
作为终止条件时使用,但通常不推荐作为通用的数组遍历方式。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END
暂无评论内容