JavaScript Promises解决了哪些突出的障碍?或者他们究竟是什么?

时间:2016-05-22 01:59:26

标签: javascript jquery ajax asynchronous promise

我已经使用JavaScript编程了几年,直到最近才听到 Promise 一词。我已经在网上阅读了多篇关于它的文章,但仍然不了解Promise是什么。我没有看到任何严格的定义。我所见过的每个例子都是一个我已经知道如何解决的问题。例如,

get('story.json').then(function(response) {
  console.log("Success!", response);
}, function(error) {
  console.error("Failed!", error);
});

来自https://davidwalsh.name/promises我会知道怎么做

$.ajax({
   url : 'story.json',
   method : 'GET',
   success : function(response) { console.log("Success!", response); },
   error : function(error) { console.error("Failed!", error); }
});

在不知道这个词的情况下,我是否使用了Promise的概念?或者我错过的大派对在哪里?

1 个答案:

答案 0 :(得分:2)

这种增加能够将事物联系起来。 如果你需要一个接一个地打三个电话,你可以将你的承诺连在一起而不是:

$.ajax({
  success () {
    $.ajax({
      success () {
        $.ajax({
          success () { /* do something with your sets of results */ }
        });
      }
    });
  }
});

相反,您可以执行以下操作:

fetch(url1).then(toJSON)
  .then(result1 => fetch(url2).then(toJSON))
  .then(result2 => fetch(url3).then(toJSON));

这两个例子并没有做同样的事情(你需要使用每个结果,或者传递出来,传递它),但基本上承诺包装你的进程并返回一个对象(带有{ {1}}方法)允许您添加回调(并继续添加回调)。