我尝试将10个插入逐个打印到数组中
const obj = []
const delay = (timer, num) => setTimeout(() => Promise.resolve(num), timer)
_.times(10).map(o => {
delay(1000, o).then(num => console.log(obj.push(num)))
})
https://jsfiddle.net/287b4daz/
但是我得到了延迟。那不是函数错误吗?或者我甚至不需要在这里使用Promise,因为setTimeout本身已经是一个承诺?
答案 0 :(得分:0)
它抱怨deplay(...).then
不是函数 - deplay
没有返回承诺。您需要使用Promise构造函数而不是Promise.resolve
:
(另外,将deplay
更改为delay
:)
const obj = []
const delay = (timer, num) => new Promise(resolve => setTimeout(() => resolve(num), timer))
_.times(10).map(o => {
delay(1000, o).then(num => console.log(obj.push(num)))
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>
&#13;
如果您想将它们链接在一起,以便每个人在运行之前等待前一个解析,请使用.reduce
:
const obj = []
const delay = (timer, num) => new Promise(resolve => setTimeout(() => resolve(num), timer));
Array.from({ length: 10 }, (_, i) => i + 1)
.reduce((lastPromise, o) => (
lastPromise
.then(() => delay(1000, o))
.then(num => console.log(obj.push(num)))
), Promise.resolve())
&#13;
答案 1 :(得分:0)
逐一打印,假设你的意思是每一秒(根据回答评论)
const obj = []
const delay = (timer, num) => new Promise(resolve => setTimeout(resolve, timer, num));
let p = Promise.resolve();
_.times(10).map(o => {
p = p
.then(() => delay(1000, o))
.then(num => console.log((obj.push(num+1), obj+'')));
})
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>
&#13;
注意... push(num+1)
如果您需要1
,1,2
等,则其为0
,0,1
等
注2:console.log(x.push(y))
记录 x的新长度,而不记录数组x - 这就是为什么我将console.log((obj.push(num+1), obj+''))
注释到内部的()
, ,
运算符,以便输出为obj+''
真的,要清楚,你应该写下来
const obj = []
const delay = (timer, num) => new Promise(resolve => setTimeout(resolve, timer, num));
let p = Promise.resolve();
_.times(10).map(o => {
p = p
.then(() => delay(1000, o))
.then(num => {
obj.push(num+1);
console.log(obj.join(','))
});
})
要指出的另一件事是.map
在这里使用是错误的,因为.map
用于将数组映射到新的值数组 - 因为您正在处理异步代码,结果数组最多是一个未定义的数组,或者是Promises数组 - 但由于你没有将.map
的结果赋给任何东西,所以这一点非常没有实际意义