异步调用后处理重定向的正确方法 [英] Correct way to handle redirect after async call

查看:52
本文介绍了异步调用后处理重定向的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果需要,我需要对服务器进行Ajax调用以更新数据.我的功能如下:

I need, if some condition meets, make ajax call to server to update data. My function looks like following:

function doSomething() {
    if (something) {
        callSomethingAsync()
    }

    window.location = "/redirecturl"
}

我的问题是,是否始终保证在重定向之前完成callSomethingAsync?

My question is, is it always guaranteed that callSomethingAsync will be finished before redirect?

推荐答案

如果您的异步调用返回了一个Promise,那么您只需 await 即可.仅当ajax调用完成并且响应作为承诺返回时,才会执行下一行代码(也可以包括重定向),例如:

If your async call returns a promise, then you can just await for it. Only when the ajax call is completed and a response is returned as a promise then only next line of codes will execute (which can include redirects also) like:

// This is a async call, can be a ajax call inside promise
// we are using setTimeout with 2s delay 
function getCoffee() {
  return new Promise(resolve => {
    // It takes 2 seconds to make coffee
    setTimeout(() => resolve('Got the ☕ after 2s'), 2000);
  });
}

// Added async to this function
async function doSomething() {
  console.log('Making coffee first');
  const coffee = await getCoffee();

  // This log will only show after async call has finished
  console.log(coffee);

  // or something like redirect
  // window.location = "/redirecturl"
}

doSomething()

这篇关于异步调用后处理重定向的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆