json解析后的Javascript回调 [英] Javascript callback after json parse

查看:139
本文介绍了json解析后的Javascript回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从不同的应用程序中提取json,并且只有当用户在该应用程序中执行某项操作时才会传递。



看看它是否等于1,然后有很多其他函数,取决于真或假需要执行,只有在此函数运行后。



我可以把所有的函数放在if语句中,但是有更好的方法使用回调吗?

  function retrieveData(retrieveDataJson){
data = JSON.parse(retrieveDataJson);
user = data.id;
if(user === 1){
//做一些东西
}
else {
//做一些其他的东西

}

}


解决方案

更好很难定义,当它涉及到编程风格,所以它很难给你的问题最好的答案,而不知道更多的你正在做什么和你的代码如何结构。



这就是说,一个好的经验法则是试图保持你的代码组织在如何描述你的问题,而不是编写只关心控制流的代码。它不是一个硬规则,但一方面,你想要避免巨大的功能,一切,但另一方面,你想避免的函数,小,跳过太多调用其他函数或回调。



首先,我们假设你的代码只是同步的。大多数语言都是这样的,它的耻辱是Javascript强制回调。你可以做的一件事是创建接收参数并返回适当值的函数。例如:

  //这将是用户管理逻辑放在一个地方
//我们如何能给这个函数一个好的名字。如果你有一个
//很难命名函数的一个提示,也许你不应该创建
//函数在第一位。
function isAdmin(userData){
return userData.id === 1;
}

如果它只是几行代码使用一次,让它们内联

  //像process X或do X这样的名称不是很描述性。 
//看到我的意思是什么会很好知道额外的上下文?
function processUser(userData){
//你的AJAX代码应该处理JSON.Parse。
//我喜欢有工作的代码接收JS对象
//因为这使得更容易测试和集成其他JS代码
//(不需要转换事物到字符串只是传递给这个函数)

if(isAdmin(userData)){
// do
//一些东西
return someValue;
} else {
//做一些其他东西
return someOtherValue;
}
}

注意,我在这里添加了明确的即使你的代码实际上并没有返回任何东西,这将有助于理解到回调的过渡。



如果你的代码太大,你可以移动到其他函数:

  function processAdmin(user){
//几十行代码...
return someValue;
}

function processUnpriviledgedUser(user){
// ...
return someOtherValue;
}

function processUser(userData){
if(isAdmin(userData)){
return processAdminUser(userData);
} else {
return processUnpriviledgedUser(userData);
}
}

function fetchUser(){
//假装AJAX是同步的...
var rawData = $。 magicAjax(www.example.com);
var user = JSON.Parse(data);
var val = proccessUser(user);
return val;
}

请注意,我们可以免费使用函数,从多个地方:

  var result = proccessUnpriviledgedUser({id:2,name:hugomg}); 
console.log(result);

现在,让我们得到回调。如果所有的processUser是同步的,你可以重构它使用正如我之前解释的功能。不幸的是,如果你想做任何AJAX调用或otehr async的东西里面,你不能依赖 return 语句像以前。相反,您需要使用 onDone 回调替换它们,这些回调接收您将返回的内容作为参数。



例如,我们的processUser可能看起来像

  function processUser(userData,onDone){
if(isAdmin )){//< - 我们仍然可以使用同步代码,不做IO
$ .ajax(bla,{success:function(){
// blaz;
onDone(someValue);
});
} else {
//
}
}

function fetchUser(onDone){
$ .ajax(www.example。 com,{
success:function(data){
var user = JSON.Parse(data);
proccessUser(function(val){
onDone(val);
});
}
});
}

function main(){
fetchUser(function(val){
console.log(Fetched the user,val);
});
}

请注意我们如何使用我们用于分割代码的相同规则函数 - 关于代码大小和名称的相同想法仍然适用。唯一的区别是,做异步东西的函数需要使用回调,而不是 return 。特别是,注意我们如何添加onDone回调到fetchUser和proccessUser。我们不仅创建了我们自己的异步函数,而且回调参数意味着我们不需要在函数结束后硬编码什么被调用 - 就像 return 回到无论调用函数调用我们, onDone callbacks意味着我们跳转到任何回调的调用者想要我们(而不是总是跳到相同的地方,一旦我们完成)。



  proccessUnpriviledgedUser({id:2,name:hugomg},function(result){
console.log );
});






最后,异步代码的大缺点是错误处理。为了处理跨异步函数的try-catch,类似于处理跨同步函数,你可能还需要传递 onError 回调以及 onDone 回调。因为这是非常锅炉,很容易得到正确,我建议使用某种类型的库来帮助管理你的异步代码(基于promise或基于cb的一个应该是OK)如果你开始写非平凡的异步代码。 / p>

I am pulling json from a different application and it only gets passed when the user does something in that application.

Once I have pulled it in I am then checking to see if it equals 1 and then have a lot of other functions depending on true or false that need to be performed and only after this function has run.

I can stick all my functions in the if statements but is there a better way using callbacks?

function retrieveData (retrieveDataJson){           
    data = JSON.parse(retrieveDataJson);
    user = data.id; 
    if (user === 1) {
    //do some stuff 
    }
    else {
        // do some other stuff

    }

}

解决方案

"Better" is hard to define when it comes to programming style so its hard to give a "best" answer to your question without knowing more about what you are doing and how your code is structured.

That said, one good rule of thumb is trying to keep your code organizing in terms of how you would describe your problem as opposed to writing code that only cares about control flow. Its not a hard rule though, on one end you want to avoid huge functions that do everything but on the other hand you want to avoid functions that are to small and jump around too much calling other functions or callbacks.

First of all, lets pretend that your code is only synchronous. Most languages are like this and its a shame that Javascript forces callbacks down on you. One thing you can do is create functions that receive parameters and return appropriate values. For example:

//This puts the "is user admin" logic in a single place
//Also note how we can give a good name for the function. If you have a 
//hard time naming the function its a hint that maybe you shouldn't be creating
//the function in the first place.
function isAdmin(userData){
    return userData.id === 1;
}

If its just a few lines of code that are used once, you can just leave them inline

// Names like "process X" or "do X" are not very descriptive.
//See what I mean by it would be good to know extra context?
function processUser(userData){
   // Your AJAX code should handle the JSON.Parse.
   // I prefer having the code that does the work receive the JS objects
   // because that makes things easier to test and to integrate with other JS code
   // (no need to convert things to string just to pass to this function)

   if(isAdmin(userData)){
       //do
       //some stuff
       return someValue;
   }else{
       //do some other stuff
       return someOtherValue;
   }
}

Note that I added explicit "returns" here. Even if your code isn't actually returning anything, this will come handy for understanding the transition to callbacks.

If your code gets too big you can move it to some other function:

function processAdmin(user){
    // dozens of lines of code...
    return someValue;    
}

function processUnpriviledgedUser(user){
    //...
    return someOtherValue;
}

function processUser(userData){
   if(isAdmin(userData)){
       return processAdminUser(userData);
   }else{
       return processUnpriviledgedUser(userData);
   }
}

function fetchUser(){
    //lets pretend that AJAX is synchronous for a moment...
    var rawData = $.magicAjax("www.example.com");
    var user = JSON.Parse(data);
    var val = proccessUser(user);
    return val;
}

Note that one thing we get for free with function is that we can call them from multiple places:

var result = proccessUnpriviledgedUser({id:2, name:"hugomg"});
console.log( result );

Now, lets get to callbacks. If all your "processUser" stuff is synchronous, you can probably refactor it using normal functions like I explained before. Unfortunately, if you want to do any AJAX call or otehr async stuff inside, you can't rely on return statements like before. Instead, you need to replace them with an onDone callback that receives as a parameter the stuff you would have returned.

For example, our processUser might look like

function processUser(userData, onDone){
    if(isAdmin(userData)){ // <-- we can still use sync code when not doing IO
        $.ajax("bla", {success: function(){
            //blaz;
            onDone(someValue);
        });
    }else{
        //
    }
}

function fetchUser(onDone){
    $.ajax("www.example.com", {
        success: function(data){
            var user = JSON.Parse(data);
            proccessUser(function(val){
                onDone(val);
            });
        }
    });
}

function main(){
    fetchUser(function(val){
        console.log("Fetched the user", val);
    });
}

Note how we can use the same rules we used to for splitting code in separate functions - the same idea about code size and names still applies. The only difference is that functions doing async stuff need to use callbacks instead of return. In particular, note how we added onDone callbacks to fetchUser and proccessUser. Not only did we create our own async functions, but the callback parameters mean that we don't need to hardcode what gets called after the function ends - just like return goes back to whatever caller function that called us, onDone callbacks means we jump to whatever callback the caller wants us to (instead of always jumping to the same place once we are done).

proccessUnpriviledgedUser({id:2, name:"hugomg"}, function(result){
    console.log(result);
});


Finally, I would like to point out that a big disadvantage of async code is the error handling. In order to handle "try-catch" across async functions similarly to how its handled across sync functions you might also need to pass around onError callbacks in addition to the onDone callbacks. Because this is very boilerplaty and very easy to get right, I would recommend using some sort of library to help manage your async code (either a promise based or cb based one should be OK) if you ever start writing non trivial async code.

这篇关于json解析后的Javascript回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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