2017-06-03 112 views
0

我正试图编写一个函数,其中包括一个for循环内的Promise,但循环只在迭代执行,并且承诺永远不会解决。For循环内没有完成Promise

我的代码如下所示:

function appendPosts() { 
    return functionThatReturnsAPromise() 
     .then(result => { 
      return new Promise((resolve, reject) => { 
       var list = []; 
       result.forEach(item => { 
       //do stuff to item 
       list.push(item); 
       }); 
      resolve(list); 
      }); 
     }) 
     .then(list => { 
      return new Promise((resolve, reject) => { 
      //This loop only runs once, even when list has contains many items 
      for (var i = 0; i < list.length; i++) { 
      document.querySelector("someSelector").appendChild(list[i]); 
      } 
      resolve(); 
     }); 
    }); 
} 

显然,我做错了什么。有任何想法吗?

谢谢你的时间。 - 丹尼尔

+0

'.then()'中'Promise'构造函数的目的是什么?为什么迭代'result'只是为了将'item'推送到数组? – guest271314

+1

我不认为当列表长度更长时,for循环只能运行一次。再次检查迭代和list.length。 – xDreamCoding

+2

也许第一次迭代发生异常?使用['catch'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch)。 –

回答

0

@MaazSyedAdeeb是正确的。循环中出现了一个异常,我没有一个catch块。谢谢。

0

选择器可能没有返回匹配,因此appendChildundefined上被调用,触发异常转换为被拒绝的承诺。

如果你打电话给你增加一个.catch你可以把这个错误:

appendPosts().then(function() { 
    console.log('all done'); 
}).catch(function (err) { 
    console.log('error occurred: ', err); 
}); 

但是,你正在使用的promise constructor anti-pattern也应该被提及。也就是说,在then回调函数中,您可以返回一个值,该值将成为then将返回的承诺的承诺值。所以不需要做new Promise()。相反,这样做:

function appendPosts() { 
    return functionThatReturnsAPromise().then(result => { 
     // Just return the mapped array: 
     return result.map(item => { 
      //do stuff to item 
      return item; 
     }).then(list => { 
      for (var i = 0; i < list.length; i++) { 
       // Make sure the selector will result in a match: 
       document.querySelector("someSelector").appendChild(list[i]); 
      } 
     }); 
    }); 
}