我有一个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) 鉴于以下示例,为什么outerScopeVar在所有情况下都未定义?
var outerScopeVar;
var img = document.createElement('img');
img.onload = function() {
outerScopeVar = this.width;
};
img.src = 'lolcat.png';
alert(outerScopeVar);
Run Code Online (Sandbox Code Playgroud)
var outerScopeVar;
setTimeout(function() {
outerScopeVar = 'Hello Asynchronous World!';
}, 0);
alert(outerScopeVar);
Run Code Online (Sandbox Code Playgroud)
// Example using some jQuery
var outerScopeVar;
$.post('loldog', function(response) {
outerScopeVar = response;
});
alert(outerScopeVar);
Run Code Online (Sandbox Code Playgroud)
// Node.js example
var outerScopeVar;
fs.readFile('./catdog.html', function(err, data) {
outerScopeVar = data;
});
console.log(outerScopeVar);
Run Code Online (Sandbox Code Playgroud)
// with promises
var outerScopeVar;
myPromise.then(function (response) {
outerScopeVar = response;
});
console.log(outerScopeVar);
Run Code Online (Sandbox Code Playgroud)
// geolocation API
var outerScopeVar; …Run Code Online (Sandbox Code Playgroud) 我在Node.js中从回调函数返回一个值时遇到小麻烦,我会尽量解释我的情况.考虑我有一个片段,它接受URL并点击该url并给出输出:
urllib.request(urlToCall, { wd: 'nodejs' }, function (err, data, response) {
var statusCode = response.statusCode;
finalData = getResponseJson(statusCode, data.toString());
});
Run Code Online (Sandbox Code Playgroud)
我试图将它包装在一个函数中并返回一个这样的值:
function doCall(urlToCall) {
urllib.request(urlToCall, { wd: 'nodejs' }, function (err, data, response) {
var statusCode = response.statusCode;
finalData = getResponseJson(statusCode, data.toString());
return finalData;
});
}
Run Code Online (Sandbox Code Playgroud)
因为在我的Node.js代码中,我有很多if-else声明urlToCall将决定其值,如下所示:
if(//somecondition) {
urlToCall = //Url1;
} else if(//someother condition) {
urlToCall = //Url2;
} else {
urlToCall = //Url3;
}
Run Code Online (Sandbox Code Playgroud)
事情是urllib.request,除了值之外,一个遗嘱中的所有陈述都保持不变urlToCall.所以我肯定需要将这些公共代码放在函数中.我尝试了同样但doCall总是会回报我undefined.我试过这样的: …
我有一个javascript函数,我想返回我在返回方法后得到的值.比说明更容易看到
function getValue(file){
var val;
lookupValue(file).then(function(res){
val = res.val;
}
return val;
}
Run Code Online (Sandbox Code Playgroud)
承诺的最佳方式是什么?据我所知,它return val会在lookupValue完成它之前返回,但是我不能return res.val因为那只是从内部函数返回.
我遇到了 get_user() 在 console.log(usersOutput, 'here') 之后运行的问题。如何更改它以便 get_user() 首先运行?
function get_user(user){
axios.get(`/api/admin/users`,{params:{idnum:user}}).then((user)=>{
console.log('got user')
return user.data
})
}
var UsersFormatter = function(c){
let usersOutput = 'waiting for change'
var usersOutput = get_user(c.cell.row.data.sessionUser)
console.log(usersOutput,' here')
return usersOutput
}
Run Code Online (Sandbox Code Playgroud) 我正在编写获取数据的代码.首先我调用**getsomedata**函数来获取数据和里面的getsomedata函数我调用另一个函数getRandomdata来获取数据并将其返回到前一个函数但它返回undefined.但在getRandomdata数据中可以看到console.log.我需要使用callbacks吗?
router.get('/get-data', function (req, res, next) {
var result = getsomedata(some_parameter);
console.log(result); // receiving undefined
res.send(result);
});
function getsomedata(some_parameter_recieved) {
var getsomedata = getRandomdata(random_params);
console.log(getsomedata); // receiving undefined
return getsomedata;
}
function getRandomdata(random_params_recieved) {
// after some calculation
console.log(random_data); // receiving proper data
return random_data;
}
Run Code Online (Sandbox Code Playgroud) 我有一个画布,我使用以下代码上传图像:
function handleImage(e){
var reader = new FileReader();
reader.onload = function(event){
var img = new Image();
img.onload = function(){
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img,0,0);
}
img.src = event.target.result;
}
reader.readAsDataURL(e.target.files[0]);
}
Run Code Online (Sandbox Code Playgroud)
现在我想使用canvas.toDataURL()它将图像加载到另一个画布.代码是:
var dataURL = canvas.toDataURL();
drawDataURIOnCanvas(dataURL,canvas2);
function drawDataURIOnCanvas(dataURL, name_of_canvas) {
var myCanvas = document.getElementById(name_of_canvas);
var img3 = new Image;
var ctx2 = myCanvas .getContext('2d');
img3.onload = function(){
ctx2.drawImage(img3,0,0); // Or at whatever offset you like
};
img3.src = dataURL;
}
Run Code Online (Sandbox Code Playgroud)
如果我把这个工作网址都搞好了.但是我试过的任何图片中产生的网址都是以
数据:图像/ PNG; BASE64,iVBORw0KGgoAAAANSUhEUgAAASwAAACWCAYAAABkW7XSAAAAxUlEQVR4nO3BMQEAAADCoPVPbQhfoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOA1v9QAATX68/0AAAAASUVORK5CYII =. …
这可能是一个简单的答案,但我正在尝试获取响应的主体并返回到另一个函数.这肯定是一个范围问题.
这是我的代码,任何想法都将非常感激:
var request = require("request");
var myJSON = require("JSON");
function getMyBody(url) {
var myBody;
request({
url: url,
json: true
}, function (error, response, body) {
if (!error && response.statusCode === 200) {
myBody = body;
}
});
return(JSON.parse(myBody));
Run Code Online (Sandbox Code Playgroud)
}
js_traverse(getMyBody(url));
Run Code Online (Sandbox Code Playgroud)
谢谢
格伦
我在单个函数(abcd)中使用回调嵌套了内部函数.
我需要使用异步从外部调用abcd函数并返回响应.
var listFunctions = {
test1 : function(objectData, callbackData) {
//have logic and retrun data
callbackData(null, "a");
},
test2 : function(objectData, callbackData) {
//have logic and retrun data
callbackData(null, "b");
},
test3 : function(objectData, callbackData) {
//have logic and retrun data
callbackData(null, "c");
},
test4 : function(objectData, callbackData) {
//have logic and retrun data
callbackData(null, "d");
},
test5 : function(objectData, callbackData) {
//have logic and retrun data
callbackData(null, "e");
}
};
function abcd(objectData, clb) {
listFunctions.test1(objectData, function(err, data1) { …Run Code Online (Sandbox Code Playgroud) 我试图val在下面的代码中为变量赋值:
var cmdValue = "/cmd/fetch?x=";
var val;
var returned_data;
function what(){
val = update('#TAG#');
}
function update(tag) {
var req1 = newXMLHttpRequest();
req1.open("GET",cmdValue + tag, true);
req1.send("");
return req1.onreadystatechange= function () {
if (req1.readyState == 4 && req1.status == 200) {
returned_data = req1.responseText;
return returned_data;
}else{
}
};
}
Run Code Online (Sandbox Code Playgroud)
我正在跟踪Firebug中的变量,事实证明它val被分配了函数.有没有办法让代码运行,然后将值赋给变量val?
javascript ×10
node.js ×6
asynchronous ×3
ajax ×2
callback ×2
jquery ×2
canvas ×1
data-url ×1
html5 ×1
node-async ×1
promise ×1
q ×1
request ×1