简体   繁体   English

连续嵌套承诺的最佳实践

[英]best practice for nesting promises in succession

I currently have a few functions that return promises such as the below:我目前有一些返回承诺的函数,如下所示:

function action_one(){
    return new Promise((resolve, reject)->{
        ...
    });
}

I want to be able to wait on one before doing the next promise without nesting them.我希望能够在执行下一个 promise 之前等待一个而不嵌套它们。 I had searched for some solutions, one being PromiseAll() but it does not seem to do it in order.我已经搜索了一些解决方案,一个是 PromiseAll() 但它似乎没有按顺序执行。 Another solution was to do the following:另一种解决方案是执行以下操作:

   promise.then(result =>{
       action
   }.then(result =>{
       action
   }.then(result =>{
       action
   }.then(result =>{
       action
   }.then(result =>{ etc.

which I'm not sure works for my issue but it doesn't seem compactable.我不确定这是否适用于我的问题,但它似乎不可压缩。

what would be best practice in this situation?在这种情况下,最佳做法是什么?

Edit:编辑:

I'm not sure how to use the.then chain with multiple promises such as:我不确定如何使用带有多个承诺的 the.then 链,例如:

promise.then(result =>{
       action
   }promise.then(result =>{
       action
   }promise.then(result =>{
       action
   }promise.then(result =>{
       action
   }promise.then(result =>{ etc.

It does not yield the result I expect它不会产生我期望的结果

I found my solution:我找到了我的解决方案:

new Promise(function(resolve, reject) {

  setTimeout(() => resolve(1), 1000);

}).then(function(result) {

  alert(result); // 1

  return new Promise((resolve, reject) => { // (*)
    setTimeout(() => resolve(result * 2), 1000);
  });

}).then(function(result) { // (**)

  alert(result); // 2

  return new Promise((resolve, reject) => {
    setTimeout(() => resolve(result * 2), 1000);
  });

}).then(function(result) {

  alert(result); // 4

});

I needed to return the promise to chain them which is why it was not working.我需要返回 promise 来链接它们,这就是它不起作用的原因。 Source: https://javascript.info/promise-chaining资料来源: https://javascript.info/promise-chaining

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM