函数,该函数从webservice返回一个值



我知道这是一个答案很高的话题,但读了很多帖子,我不知道我的dilema是否有我想要的解决方案。

我想写一个简单的函数,返回传递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];
}

但是,我没有固定的users对象,而是从我的php-webService中检索它,该服务从DB中获取它。

使用回调使得无法处理值。例如(如果我使用回调并假设调用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

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

我已经读过如何从异步调用返回响应?更像这样,也更容易理解,但我无法理解如何使用来自不同来源的检索值并应用必要的逻辑。Basicly,如何秩序混乱?

看起来您正在经历回调地狱。当您有几个异步函数,并且需要处理它们的所有错误和成功时,就会发生这种情况。

正是在这种情况下,承诺才被发明出来。

如果您没有ES6,请查看jquery promise,否则它们是内置的: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);
});

最新更新