我有一个foo发出Ajax请求的函数.我怎样才能从中回复foo?
我尝试从success回调中返回值,并将响应分配给函数内部的局部变量并返回该变量,但这些方法都没有实际返回响应.
function foo() {
var result;
$.ajax({
url: '...',
success: function(response) {
result = response;
// return response; // <- I tried that one as well
}
});
return result;
}
var result = foo(); // It always ends up being `undefined`.
Run Code Online (Sandbox Code Playgroud) 我正在从Angular的文档中看到这个例子,$q但我认为这可能适用于一般的承诺.他们有这个例子,逐字复制他们的评论包括:
promiseB = promiseA.then(function(result) {
return result + 1;
});
// promiseB will be resolved immediately after promiseA is resolved and its value
// will be the result of promiseA incremented by 1
Run Code Online (Sandbox Code Playgroud)
我不清楚这是如何工作的.如果我可以调用.then()第一个的结果.then(),链接它们,我知道我可以,那么promiseB是一个类型的promise对象Object.它不是Number.那么他们的意思是"它的价值将是promiseA增加1的结果"?
我应该promiseB.value像那样访问它吗?成功回调如何返回一个承诺并返回"结果+ 1"?我错过了什么.