简体   繁体   中英

async/await timeout after fadeout when fadein is done

I've this piece of code which basically does: --When the ajax (promise) is executed: -Fadeout, and when the fadeout finished: --Fade in:

async function loadForm (data) {

   let promiseForm = pForm(data);
   await promiseForm.then(function(data) {

          setTimeout(function () {

            $container.fadeOut(function() {
                $container.append(msg);
                $container.fadeIn();
            });

          }, 800);
    });

}

But now i need handle then all this is done

I've tried this code but didn't worked because the Jquery selector is executed before the fadeout callback, so $container html hasn't been appended yet.

async function loadForm (data) {

 let promiseForm = pForm(data);
 await promiseForm.then(function(data) {

        setTimeout(function () {

          $container.fadeOut(function() {
              $container.append(msg);
              $container.fadeIn();
          });

        }, 800);

  });

}
async function checkActiveForm() {

  let promiseActiveForm = pCheckActiveForm
  await promiseActiveForm.then((json) => {

          loadForm(data).then(function() {
              $(document).find("#"+logEvento.id).prop('checked',true); 
              //This element is created on the $container.append(msg) of "A" function
          });
  });

}


SOLVED:

async function loadForm (data) {

   let promiseForm = pForm(data);
   var msg ;
   await promiseForm.then(function(data) {
       msg = response;
    });

    await new Promise(res => {
       setTimeout(function () {

          $container.fadeOut(function() {
             $container.append(msg);
             $container.fadeIn();

             res();
          });

        }, 800);
    }

}

JavaScript isn't aware that the setTimeout is asynchronous, and you aren't telling it in any way. You should tell that in the setTimeout callback the flow is synced again.

Instead, you are launching a timeout and going ahead (and no matter if it's inside a promise.).

Furthermore, your await is useless, because you are waiting two promises to solve, but you aren't doing anything after that you waited.

Maybe you meant something like this:

await promiseForm; // Wait the first promise
await new Promise (res => { // Wait the timeout
      setTimeout(function () {
        $container.fadeOut(function() {
            $container.append(msg);
            $container.fadeIn();
            res();
        });
      }, 800);
});
// Do something after that everything happened

PS. Are the two promises needed to be executed in sequence? Can't you parallelise them (getting a performance improvement)?

Maybe you could use Promise.all

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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