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

时间:2018-05-17 01:31:07

标签: javascript ecmascript-6 lodash

我尝试将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本身已经是一个承诺?

2 个答案:

答案 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;
&#13;
&#13;

如果您想将它们链接在一起,以便每个人在运行之前等待前一个解析,请使用.reduce

&#13;
&#13;
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;
&#13;
&#13;

答案 1 :(得分:0)

逐一打印,假设你的意思是每一秒(根据回答评论)

&#13;
&#13;
    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;
&#13;
&#13;

注意... push(num+1)如果您需要11,2等,则其为00,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的结果赋给任何东西,所以这一点非常没有实际意义