一个关于promise的问题!!!
发布于 6 年前 作者 MeetTheBest 3341 次浏览 来自 问答

请大佬们帮忙看看, 那个index为啥每次都是最后一次的值(第五行的那个index).

promise_problem.png

6 回复

看一下闭包,就理解了, 要把index传入

@LeoChowChina 您好, 多谢您的帮忙, 不过我通过 添加一个自执行函数 好像也没有效果

((index) => {
	// code
})(index)
const resolvePromise = Promise.resolve();
const pormiseAll = [1, 2, 3, 4].map((item, index) => {
	return resolvePromise.then(async res => {
		return item * index;
	});
});

Promise.all(pormiseAll).then(res => {
	console.log(res);
});
//[ 0, 2, 6, 12 ]

在第三行添加 let fixIndex = index; 把第五行index改为fixIndex;

回到顶部