1

How do I make chain two JQuery async calls using JS Promises while avoiding the pyramid of doom? I know that I can convert a "JQuery" promise to a real promise like this:

Promise.resolve($.getJSON(url, params));

If I just want to wait for one promise, I can do this:

Promise.resolve($.getJSON(url1, params1))
.then(function(result){
  // do stuff
});

If I want to wait for two different ajax calls to be done, I can do this:

Promise.all(
[
  Promise.resolve($.getJSON(url1, params1)),
  Promise.resolve($.getJSON(url2, params2))
]).then(function(results_array){
  // do stuff
});

However, if I want one call to come after the other one, this doesn't work:

Promise.resolve($.getJSON(url1, params1))
.then(function(result){
  //do stuff
  return Promise.resolve($.getJSON(url2, params2));
}).then(function(result){
  //result is a promise, not the results from the second call to getJSON()...
  //and it doesn't even wait for the second call to finish.
  //result.then() is just going to bring me further into the pyramid of doom :(
});

Somehow, I want to call .then() on the promise constructed in the "do stuff" function. What's the idiomatic way to do this?

4

1 回答 1

3
return Promise.resolve($.getJSON(url2, params2));

你所做的是创建一个已经解决的承诺(通过Promise.resolve)承诺,其解决的价值是的结果$.get(),这也是一个承诺。这就是为什么“它甚至不等待第二次调用完成”和“结果是一个承诺”。

此外,您不需要包装 jQuery AJAX 调用,因为它们返回承诺。jQuery 的 Promise 的行为几乎(但不完全)与原生 Promise 相同。

改为这样做:

$.getJSON(url1, params1).then(function(result)){
  return $.getJSON(url2, params2);
}).then(function(result)){
  //result 2
});

此外,您正在使用 jQuery。带有 Promise 的 jQuery AJAX 可以这样完成:

$.getJSON(url1, params1).then(function(result){
  // do stuff
});

在 jQuery 中可以通过这种方式监听多个 Promise:

$.when($.getJSON(...), $.getJSON(...)).then(function(res1, res2){
  // do stuff
});
于 2015-07-08T20:48:12.273 回答