【问题标题】:async/await timeout after fadeout when fadein is done淡入完成后淡出后的异步/等待超时
【发布时间】:2020-02-02 19:41:51
【问题描述】:

我有这段代码,它基本上可以: -- ajax(promise)执行时: - 淡出,以及淡出完成时: --淡入:

async function loadForm (data) {

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

          setTimeout(function () {

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

          }, 800);
    });

}

但现在我需要处理所有这一切

我试过这段代码但没有成功,因为 Jquery 选择器是在淡出回调之前执行的,所以 $container html 还没有被追加。

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
          });
  });

}


已解决:

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 jquery asynchronous promise async-await


    【解决方案1】:

    JavaScript 不知道 setTimeout 是异步的,而且您也不会以任何方式告诉它。您应该在setTimeout 回调中告知流程再次同步。

    相反,您正在启动超时并继续(无论它是否在承诺中!)。

    此外,您的 await 是无用的,因为您正在等待两个 Promise 来解决,但在等待之后您什么也没做。

    也许你的意思是这样的:

    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。两个promise需要依次执行吗?您不能将它们并行化(提高性能)吗?

    也许你可以使用Promise.all

    【讨论】:

    • 我无法使用Promise.all,因为$container.append(msg) 的内容取决于promiseForm 的响应,我正在研究如何实现上面的代码并将给出我的答案!谢谢!
    • 解决了!谢谢!但是,如果 setTimeoutawait promiseForm.then(); 中,javascript 不会等待 promise 和 .then(); 回调来完成执行?
    猜你喜欢
    • 2012-01-03
    • 2013-03-17
    • 2012-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多