1

我正在尝试编写一些让我调用承诺函数或更多内部函数的函数。

我现在正在做的是这样的

myFunction(){
   this.function1().then(data1=>{
      this.function2().then(data2=>{
         //do something
      })
   });
}
function1(){
   return new Promise (response=>{
      //do something
      response(data1);
   })
}
function2(){
   return new Promise (response=>{
      //do something
      response(data2);
   })
}

有什么简单的方法可以在 myFunction() 中运行 function1() 和 function2() 吗?

编辑:

我需要一些如何编写 1 个函数而不是像这样的 3 个函数

myFunction(){
   //something here to return data1 and continue
      //same thing here to return data2 and continue
          //do something 
} 
4

2 回答 2

2

就像特里在他的评论中说的,把myFunction改成这样的async函数:

async myFunction(){
   await this.function1();
   await this.function2();
}

function1(){
   return new Promise (response=>{
      //do something
      response(data1);
   })
}

function2(){
   return new Promise (response=>{
      //do something
      response(data2);
   })
}

于 2020-05-10T00:05:29.520 回答
2

如果你只想使用一个函数而不使用异步,你可以这样做:

myFunction(){
   (new Promise (response=>{
      //do something
      response(data1);
   }))
   .then(data1=>{
      (new Promise (response=>{
      //do something
      response(data2);
   }))
   .then(data2=>{
         //do something
      })
   });
}

不知道你为什么想要这个。它只会让事情变得更糟,根本不会简化任何事情。async方式是很多面糊。但是给你。

于 2020-05-10T00:11:26.030 回答