在异步调用后处理重定向的正确方法

时间:2018-01-28 14:42:41

标签: javascript ajax

如果某些条件满足,我需要对服务器进行ajax调用以更新数据。我的功能如下:

private void BottomView1() {
    navigation = (AHBottomNavigation) findViewById(R.id.navigation);

    AHBottomNavigationItem item1 = new AHBottomNavigationItem("Home", R.drawable.ic_home, R.color.ash);
    AHBottomNavigationItem item2 = new AHBottomNavigationItem("Category", R.drawable.ic_category, R.color.ash);
    AHBottomNavigationItem item3 = new AHBottomNavigationItem("Search", R.drawable.ic_search, R.color.ash);
    AHBottomNavigationItem item4 = new AHBottomNavigationItem("Offers", R.drawable.ic_offers, R.color.ash);
    AHBottomNavigationItem item5 = new AHBottomNavigationItem("Cart", R.drawable.ic_cart, R.color.ash);

    navigation.addItem(item1);
    navigation.addItem(item2);
    navigation.addItem(item3);
    navigation.addItem(item4);
    navigation.addItem(item5);

    navigation.setCurrentItem(getResources().getColor(R.color.colorPrimaryDark));

    navigation.setTitleState(AHBottomNavigation.TitleState.ALWAYS_SHOW);

    setCartNotification();

    navigation.setAccentColor(getResources().getColor(R.color.colorPrimaryDark));

    navigation.setOnTabSelectedListener(new AHBottomNavigation.OnTabSelectedListener() {
        @Override
        public boolean onTabSelected(int position, boolean wasSelected) {
            Intent ii ;
            Fragment selectedFragment = null;
            if(position==0){
                selectedFragment = HomeFragment.newInstance();
                FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
                transaction.replace(R.id.frame_layout_fragment, selectedFragment);
                transaction.commit();
            } else if(position==1){
                ii = new Intent(HomeActivity.this, ShopByCategoryActivity.class);
                startActivity(ii);
            } else if(position==2){
                ii = new Intent(HomeActivity.this, SearchActivity.class);
                startActivity(ii);
            } else if(position==3){
                ii = new Intent(HomeActivity.this, OffersActivity.class);
                startActivity(ii);
            } else if(position==4){
                ii = new Intent(HomeActivity.this, MyCartActivity.class);
                startActivity(ii);
            }
            return true;
        }
    });
    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    transaction.replace(R.id.frame_layout_fragment, HomeFragment.newInstance());
    transaction.commit();
}

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

3 个答案:

答案 0 :(得分:1)

您的代码正在逐行执行。如果它只包含同步操作,那么可以保证重定向在完成处理之前的任何代码之后发生。

但是,由于callSomethingAsync是异步调用,因此您不能指望它在window.location触发之前始终完成。

如果你想确定它,你可以将重定向行包含在callSomethingAsync函数的最后一步,或者你将函数扩展为进行回调。

答案 1 :(得分:1)

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



// 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()




答案 2 :(得分:0)

这是一个基本的html起始页:

<html>
<head>
<meta charset="UTF-8">
<title>Stack Overflow Test Redirect</title>
<script
  src="https://code.jquery.com/jquery-3.3.1.min.js"
  integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
  crossorigin="anonymous"></script>
</head>

<body>
Content of the document......
</body>

</html>

Js与JQuery合作:

$.ajax({

    url: '/test/', 
    type: 'GET',
    crossDomain: true, 
    success: function() { alert("Success"); },
    error: function() { alert('Failed!'); } 
});

和Vanilla JS的例子:

function makeRequest (method, url, done) {
  var xhr = new XMLHttpRequest();
  xhr.open(method, url);
//   xhr.withCredentials = true; <--CORS ENABLED!
  xhr.onload = function () {
    done(null, xhr.response);
  };
  xhr.onerror = function () {
    done(xhr.response);
  };
  xhr.send();
}

// And we'd call it as such:

makeRequest('GET', '/test.com/', function (err, datums) {
  if (err) { throw err; }
  console.log(datums);
});

小心CORS。 希望它有所帮助..