包括另一个异步等待承诺的承诺-如何解决?

时间:2020-03-24 12:07:17

标签: javascript promise async-await

我需要连续发出两个帖子请求。有一个异步的“ post form”功能,该功能以“ await”关键字开始请求,结果在“ then”块中处理。

我尝试通过等待Promise来执行此发布请求,其中我调用了上述异步函数。问题在于,似乎不能在功能"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();

我该如何解决第一个承诺,还是不可能?还有其他解决方案吗? 这个想法是在第一个请求解决后再发出一个发布请求。

1 个答案:

答案 0 :(得分:1)

如果您使用诺言,那么您将使用.then().catch(),如果您使用async/ await,那么您将不使用.then().catch(),因为异步/等待是合成糖,因此我们不需要一遍又一遍地嵌套我们的响应。

例如,如果您想使用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});

}