函数内的承诺得到错误不是函数错误

艾丽莎·肯尼迪

我尝试将 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] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章