【问题标题】:Promise which inludes another async await promise - how to resolve?包含另一个异步等待承诺的承诺 - 如何解决?
【发布时间】:2020-07-04 22:20:18
【问题描述】:

我需要连续发出两个帖子请求。有一个异步“post form”函数,它使用“await”关键字启动请求,结果在“then”块中处理。

我尝试通过等待一个承诺来完成这个发布请求,其中我调用了上面提到的异步函数。问题在于,似乎无法在函数"then" 块内解决承诺。

我有一些示例代码来显示问题(查看 start() 函数的开始位置)。见fiddle

//Returns a promise. It contains another async-await promise
function mainFunction() {

  return new Promise( () => {           //<-- this never resolves

       async function postForm(){

          //(Post a form)
         await new Promise( (resolve, reject) => {
              setTimeout(() => {
                resolve('resolved');
              }, 2000);

          }).then( response => {    // <-- how to resolve the first promise inside here?

               console.log('promise 2 response: ',response) 

               //Try to resolve the 1st promise (doesn't work)
               new Promise( (resolve,reject) => resolve('promise 1 resolved') );

          }).catch( error => {
              console.log(error)
          }) 
      }
      postForm();

  })

}

//Make two posts in succession
async function start(){ 

  //Post 1 - (never resolves)
  await mainFunction().then( response => {

        //(Next: make post request 2)

  }).catch( error => {
      console.log(error)
  })
}

start();

我怎样才能解决第一个承诺,还是不可能?还有其他解决方案吗? 我们的想法是在第一个请求解决后发出另一个发布请求。

【问题讨论】:

  • 这里有很多错误,这不是 promises / async await 的工作原理
  • mainFunction() 返回的 Promise 永远不会解决,这绝对不足为奇。没有尝试解决它。如果mainFunction()的目的是模拟一些异步过程,那么就直接写function mainFunction() { return Promise.resolve(); }吧。
  • async/await.then() 的替代语法。避免将两者混为一谈。

标签: javascript promise async-await


【解决方案1】:

如果你使用 Promise,那么你使用 .then().catch() 如果你使用 async/ await 那么你不要使用 .then().catch() 因为 async / await 是语法糖,所以我们不需要嵌套我们一遍又一遍的回应。

如果您想使用 axiosfetch 发出 2 个帖子请求,那么您可以简单地使用 async / await,因为它们会返回一个承诺。

async function requests(){
   //await makes the request wait till it gets some response
   const response1 = await axios.post("url", {data});
   const response2 = await axios.post("url2", {data});

}

【讨论】:

  • 如何使用此代码处理错误响应(如 500 服务器错误)?我正在使用一个已经存在的函数,该函数发布表单并处理结果为“then”。所以我修改了它并使其异步。也许我需要完全改变它,但它可能会产生后果,因为在我不需要以这种连续方式做事的其他情况下会调用它。
  • 看来我可以使用 try catch 来处理它们。所以这可能会奏效..
猜你喜欢
  • 1970-01-01
  • 2021-11-09
  • 1970-01-01
  • 2017-06-15
  • 1970-01-01
  • 2019-04-29
  • 2018-04-17
  • 2018-03-13
  • 2020-04-21
相关资源
最近更新 更多