简体   繁体   English

Javascript异步到同步任务

[英]Javascript Asynchronous to Synchronous task

I have the following code (these codes are in separated js files ) : 我有以下代码(这些代码在单独的js文件中):

Code 1 (home.js): 代码1(home.js):

alert('1');
BeginGetDashboardsMethod();
alert('5');

Code 2(script.js) : 代码2(script.js):

function BeginGetDashboardsMethod(){

var stop = 'false';
alert('2');
try {        
        Service.GetDashboardsMobile("" + curr_cod_user, SuccessGetDashboardMethod, ErrorGetDashboardMethod);

}
catch (e) {

}
function SuccessGetDashboardMethod(result) {
    alert('3');        
    json = result;

    json = JSON.parse(json);        
    ListDashboards(json);
}
function ErrorGetDashboardMethod(err) {
    alert(JSON.stringify(err));
}

function ListDashboards(json) {
    alert('4');
    for (var i = 0; i < json.Dashboards.length; i++) {
        if (json.Dashboards.length === 1)
            Items = "[{key:\'" + json.Dashboards[i].OBV_ST_TITULO + "\', title:\'" + json.Dashboards[i].OBV_ST_TITULO + "\'}]";
        else {
            if (i == 0) {
                Items += "[{key:\'" + json.Dashboards[i].OBV_ST_TITULO + "\', title:\'" + json.Dashboards[i].OBV_ST_TITULO + "\'} ";
            }
            else if (i + 1 == json.Dashboards.length) {
                Items += ",{key:\'" + json.Dashboards[i].OBV_ST_TITULO + "\', title:\'" + json.Dashboards[i].OBV_ST_TITULO + "\'}] ";
            }
            else {
                Items += ",{key:\'" + json.Dashboards[i].OBV_ST_TITULO + "\', title:\'" + json.Dashboards[i].OBV_ST_TITULO + "\'} ";
            }
        }

    }
    obj = eval(Items);
}     }

My code works asynchronous. 我的代码异步运行。 After Service.GetDashboardsMobile call the code "skip" Success callback and execute alert(5); 在Service.GetDashboardsMobile之后,调用代码“跳过”成功回调并执行alert(5); while executing callback. 在执行回调时。 Is there a way to make that functions synchronous? 有没有办法使这些功能同步?

To be more exactly, I want that sequence : alert('1');-->alert('2');-->alert('3');-->alert('4');-->alert('5') 更确切地说,我想要这样的序列:alert('1');-> alert('2');-> alert('3');-> alert('4');->警报('5')

Welcome to the new world of Promises. 欢迎来到承诺的新世界。

script.js script.js

alert("1"); // script 1 loaded

function $dashboard(user) {

  function getDashboard(start, limit) {
    var user = user;

    return new Promise(function(pass, fail) {

       if( Math.random()*3 > 2 ) {
         fail(new Error("boo hoo"));
       } else {
         window.setTimeout(pass, 5000, '{"time": 5000, "content": "foo"}');
       }
    });
  }

  function parseData(json) {
    return new Promise(function(pass, fail) {
      try {
        pass(JSON.parse(json));
      } catch(e) {
        fail(e);
      }
    });
  }

  function printData(data) {
    alert(JSON.stringify(data));
    return true;
  }

  return {
    get: getDashboard,
    parse: parseData,
    print: printData
  };
}

home.js home.js

(function(d,w,$) {

alert("2"); // script 2

var dashboard = $("mcfoobar");

dashboard
  .get(0, 100)
  .then(function(sData) {
     alert("3"); // data retrieved
     return dashboard.parse(sData); 
  })
  .then(function(oData) {
     alert("4"); // data parsed
     return dashboard.print(oData);
  })
  .then(function(result) {
     alert("5"); // data printed
  })
  .catch(function(err) {
    alert(JSON.stringify(err)); // Something went wrong
  });

}(document, window, $dashboard));

Notes: 笔记:

  • Why all the alerts? 为什么所有警报? Surely console.log(..) is a much better solution. 当然console.log(..)是一个更好的解决方案。 Certainly a lot less clicking. 当然少了很多点击。
  • You will have to make sure script.js is loaded. 您必须确保已加载script.js Hopefully home.js has some sort of el.onload event on the <script> element of script.js. 希望home.js在script.js的<script>元素上具有某种el.onload事件。
  • For backward compatibility you will need to have a definition of Promises just in case. 为了向后兼容,以防万一,您需要定义Promises But that should be easy to implement. 但这应该很容易实现。 You can use v8 version if it doesn't already exist in some compatibility library. 如果某些兼容性库中尚不存在v8版本,则可以使用。
  • Make sure you note how values are changed in the chain by returning different values in the .then() function. 确保通过在.then()函数中返回不同的值来记下链中值的更改方式。 To keep original values simply forward parameters. 要保留原始值,只需转发参数即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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