javascript - 从 webservice 返回值的函数

标签 javascript jquery

我知道这是一个高度回答的话题,但是阅读了大量的帖子我无法确定我的困境是否有我想要的解决方案。

我想编写一个简单的函数来返回传递 UserId 的用户名。它将在任何地方用于多种用途。

function getUserName(userId) {
    //...some code to retrieve the Name from a REST webservice like $.ajax or $.getJSON or anything else that helps me achieve my need
    return name;
}

$('#txtUserName').val(getUserName(sessionStorage.userId));
//...
if (getUserName(sessionStorage.userId) == getUserName($('#inputUser').val())) {
    alert('Error: User typed with the same name as '+ sessionStorage.userID);
}

我知道可以重写它以放置回调或其他任何东西,但我想知道是否有任何实现可以编写这个从 PHP webService 返回值的简单函数。

我想象这样一个函数:

function getUserName(userId) {
    var users ={
        'me': 'Seak Oink'
        , 'you': 'Who knows'
        , 'jd': 'John doe'
    };
    return users[userId];
}

...但是我没有固定的用户对象,而是从我的 php webService 中检索它,该服务从数据库中获取它。

使用回调,无法处理值。例如(如果我使用回调并假设调用 getUserName(userId, callback) 处理函数调用):

$('#txtUserName').val('');
getUserName(sessionStorage.userId, function(userName) {
    $('#txtUserName').val(userName);
});
if ($('#txtUserName').val() == '') {
    alert('user '+ sessionStorage.userId +' doesn't exist');
}

相反,你可以回答我将它放入回调中,但如果需要再次调用我的函数,我必须一次又一次地将它嵌套到回调中......我认为这是一个糟糕的编程习惯:

$('#txtUserName').val('');
getUserName(sessionStorage.userId, function(userName) {
    $('#txtUserName').val(userName);
    getUserName($('#inputUser').val(), function (userName2) {
        if (userName2 == userName) {
            alert('Error: User typed with the same name as '+ sessionStorage.userID);
        }
        //....here I must continue the code flow instead of continuing to caller's flow.
        //...nesting, and more nesting... impossible to read code?¿¿?:
        userpermission(userId, function(bAllowed) {
           if (bAllowed) {
              saveRecord(userId, sKey, sSomeText, function () {
                 alert('record saved -or not-');
                 // ...and continue nesting
              });
           } else {
             alert('forbidden');
           }
        });
    });
});

...而不是这个简单的代码流逻辑:

var lOk = false;
$('#txtUserName').val('');
$('#txtUserName').val(getUserName(sessionStorage.userId);
if ($('#inputUser').val() == getUserName($('#inputUser').val())) {
   alert('Error: User typed with the same name as '+ sessionStorage.userID);
}
if (userpermission(userId)) {
   lOk = saveRecord(userId, sKey, sSomeText);
} else {
   alert('forbidden');
}
if (lOk) {
  alert('record saved');
}
// ...continue the validation process or whatever

我理解使用回调检索值的简单示例,但不要在代码逻辑中使用它。

我已经读过How do I return the response from an asynchronous call?以及更多类似的东西并且可以理解,但是我无法理解如何使用从不同来源检索到的值并应用必要的逻辑。基本上,如何对困惑进行排序?

最佳答案

您似乎遇到了 callback hell . 当您有多个异步函数并且您需要处理它们的所有错误和成功时,就会发生这种情况。

这正是发明 promises 的情况。

如果您没有 ES6,请查看 jquery promises ,否则它们是内置的:ES6 promise

它们允许更可读、更同步的代码。

例如,你可以这样写代码:

 $.when( // waits for two promises to be resolved
        getUserName(userId)
            .then(function(name) {  // once name resolved, fetch profile (new promise)
                return getUserProfile(name); 
            }),
        getUserPoints(userId) // another independent promise
   ).done(function(userProfile, userPoints) { // the two above are done, I can move on and update the DOM
       $("#profile").doSomething(userProfile); 
       $("#points").doOtherThing(userPoints);
   });

关于javascript - 从 webservice 返回值的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37629305/

相关文章:

javascript - Dynamoose - 无法查询和使用 2 个键的位置

javascript - 自定义 Native Base 选项卡

javascript - Jquery ajax 调用在每个请求上呈指数增长

jQuery:如何让 jQuery.getJSON() 调用的 URL 在浏览器地址栏中可见?

php - 如何知道网址是音频还是视频?

javascript - 循环浏览导航栏的列表项并使用 jQuery 的 fadeIn() 动画使它们淡入

javascript - 从 javascript 对象中的命名键获取值

javascript - 对齐打印页面底部的div

jquery - VideoJS 播放器和播放列表没有响应

javascript - 模式框关闭后如何在屏幕上显示文本?