代码之家  ›  专栏  ›  技术社区  ›  Jason

在promise中调用函数

  •  1
  • Jason  · 技术社区  · 8 年前

    我试图找到一种方法来调用pageLoader方法。在这个承诺中争取两次。我已经尝试在一个新的承诺中分离它,但当我尝试获取变量链接[0]时,我没有定义。怎么做?

    pageLoader
      .fetch(url)
      .then(function(data) {
        links = html.orderdList(data);
      })
      .then(function() {
        return pageLoader.fetch(links[0]);
        //links[0] is undefined in the next line!?
      })
      .then(
        pageLoader
          .fetch(links[0])
          .then(function(innerLinks) {
            calLinks = html.unorderList(innerLinks);
          })
          .then(function() {
            return pageLoader.fetch("http:///example.com");
          })
          .catch(function(error) {
            console.log(error);
          })
      );
    
    2 回复  |  直到 8 年前
        1
  •  2
  •   Mark    8 年前

    你就快到了。你有一些多余的, then() s、 我已经删除了。不清楚你为什么打电话 pageLoader.fetch(links[0]) 两次它是否返回不同的结果?

    您看起来还设置了一些全局变量( links & calLinks 例如),但不清楚如何异步访问它们。

    这应该会更好一些,但鉴于上述情况,它可能仍然存在问题:

    pageLoader.fetch(url)
    .then(function(data) {
      links = html.orderdList(data); // <-- are these global or should you have a var?; 
      return pageLoader.fetch(links[0]);
    })
    .then(function(link) { // <-- did you want to do something with the return from above?
      return pageLoader.fetch(links[0])
    })
    .then(function(innerLinks) {
        calLinks = html.unorderList(innerLinks); // <-- are these global?;
        return pageLoader.fetch("http:///example.com");
    })
    .catch(function(error) {
        console.log(error);
    })
    
        2
  •  1
  •   Briley Hooper    8 年前

    线路 .then(pageLoader.fetch(links[0])...) 不是做你想做的事。这样称呼相当于这样做:

    var myCallback = pageLoader.fetch(links[0]).then().then().catch();
    
    pageLoader
      .fetch(url)
      .then(function(data) {
        links = html.orderdList(data);
      })
      .then(function() {
        return pageLoader.fetch(links[0]);
      })
      .then(myCallback)
    

    实际上,您的第二次抓取是在执行其他操作之前立即执行的,并且 后果 其中的一个被传递为回调。您可能希望在第一次调用之前不要调用该代码 fetch 已经发生,所以您希望将其包装在函数中(就像与其他 .then() 声明)。

    我还建议您可以大大简化代码:

    pageLoader
      .fetch(url)
      .then(function(data) {
        // this is called when the first fetch() returns
        links = html.orderdList(data);
        return pageLoader.fetch(links[0]);
        // returning a promise means that following .then()
        // statements will act on the returned promise rather than the original
      })
      .then(function(innerLinks) {
        // this is called when the second fetch() returns
        calLinks = html.unorderList(innerLinks);
        return pageLoader.fetch("http:///example.com");
      })
      .catch(function() {
        // this is called if the original promise or any of
        // the promises returned in the .then() callbacks throw errors
      });
    

    我发现本文非常有助于解释使用承诺的最佳方式,以及可能发生的一些错误: https://pouchdb.com/2015/05/18/we-have-a-problem-with-promises.html

    推荐文章