如何在第一次调用后重新调用承诺

How to I re-invoke the promise after the first call?

本文关键字:调用 承诺 新调用 第一次      更新时间:2023-09-26
如何在

第一次调用后重新调用承诺?

我有这个问题,.then仅在第一次点击后执行一次,之后您将不会在任何点击时执行此console.log("Success!", response);。但我需要它来回收。可能吗?

用法:

$( document ).ready(function() {
    get('http://api.icndb.com/jokes/random').then(function(response) {
        console.log("Success!", response);
      }, function(error) {
        console.error("Failed!", error);
    });
});

承诺功能:

function get(url) {
  // Return a new promise.
  return new Promise(function(resolve, reject) {
      $(".promise").click(function(){
          // do lots of other stuff here...
           // Do the usual XHR stuff
            var req = new XMLHttpRequest();
            req.open('GET', url);
            req.onload = function() {
              // This is called even on 404 etc
              // so check the status
              if (req.status == 200) {
                // Resolve the promise with the response text
                resolve(req.response);
              }
              else {
                // Otherwise reject with the status text
                // which will hopefully be a meaningful error
                reject(Error(req.statusText));
              }
            };
            // Handle network errors
            req.onerror = function() {
              reject(Error("Network Error"));
            };
            // Make the request
            req.send();
      });
  });
}

.html

<a href="#" class="promise">Promise</a>
编写

自己的promisified get()函数并没有错,这正是jQuery的$.ajax()或Angular的$http(和其他)给你的。

您需要做的就是稍微重新排列代码,以便:

  • get() 是一个通用实用程序,不依赖于特定事件
  • 根据需要从事件处理程序调用get()
$(function() {
    function get(url) {
        return new Promise(function(resolve, reject) {
            var req = new XMLHttpRequest();
            req.open('GET', url);
            req.onload = function() {
                if (req.status == 200) {
                    resolve(req.response);
                } else {
                    reject(Error(req.statusText));
                }
            };
            req.onerror = function() {
                reject(Error("Network Error"));
            };
            req.send();
        });
    }
    $(".promise").click(function() {
        // do lots of other stuff here...
        get('http://api.icndb.com/jokes/random').then(function(response) {
            console.log("Success!", response);
        }, function(error) {
            console.error("Failed!", error);
        });
    });
});

我在这里所做的只是将您的代码行移动到不同的顺序。

正如我在评论中所解释的,一个承诺只能使用一次。 一旦它被解析或拒绝,它的状态就会被永久设置,它永远不会再调用现有的.then()处理程序。 因此,您不能对每次事件发生时要调用的内容使用承诺。 您可能会回到这样的回调,这似乎非常适合这种情况:

$( document ).ready(function() {
    get('http://api.icndb.com/jokes/random', function(response) {
        console.log("Success!", response);
      }, function(error) {
        console.error("Failed!", error);
    });
});
function get(url, success, fail) {
    $(".promise").click(function(){
      // do lots of other stuff here...
       // Do the usual XHR stuff
        var req = new XMLHttpRequest();
        req.open('GET', url);
        req.onload = function() {
          // This is called even on 404 etc
          // so check the status
          if (req.status == 200) {
            // Resolve the promise with the response text
            success(req.response);
          }
          else {
            // Otherwise reject with the status text
            // which will hopefully be a meaningful error
            fail(Error(req.statusText));
          }
        };
        // Handle network errors
        req.onerror = function() {
          fail(Error("Network Error"));
        };
        // Make the request
        req.send();
    });
}