我尝试将 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 本身已经是一个承诺?
它抱怨这deplay(...).then
不是一个函数——它deplay
不返回一个 Promise。您需要使用 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>
如果要将它们链接在一起,以便每个人在运行之前等待前一个解析,请使用.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())
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句