Tag: asynchronous

如何从asynchronouscallback函数返回值?

这个问题在SO中被多次提出。 但是我仍然无法得到东西。 我想从callback中获得一些价值。 看看下面的脚本澄清。 function foo(address){ // google map stuff geocoder.geocode( { 'address': address}, function(results, status) { results[0].geometry.location; // I want to return this value }) } foo(); //result should be results[0].geometry.location; value 如果我尝试返回该值只是“未定义”。 我跟从了一些想法,但仍然失败。 那些是: function foo(address){ var returnvalue; geocoder.geocode( { 'address': address}, function(results, status) { returnvalue = results[0].geometry.location; }) return returnvalue; } foo(); […]

我怎样才能asynchronous上传文件?

我想用jQueryasynchronous上传文件。 这是我的HTML: <span>File</span> <input type="file" id="file" name="file" size="10"/> <input id="uploadbutton" type="button" value="Upload"/> 在这里我的Jquery代码: $(document).ready(function () { $("#uploadbutton").click(function () { var filename = $("#file").val(); $.ajax({ type: "POST", url: "addFile.do", enctype: 'multipart/form-data', data: { file: filename }, success: function () { alert("Data Uploaded: "); } }); }); }); 而不是被上传的文件,我只获取文件名。 我能做些什么来解决这个问题? 当前解决scheme 我正在使用jQuery表单插件来上传文件。

为什么我的variables在函数内部修改后没有改变? – asynchronous代码引用

给出以下示例,为什么在所有情况下outerScopeVar定义outerScopeVar ? var outerScopeVar; var img = document.createElement('img'); img.onload = function() { outerScopeVar = this.width; }; img.src = 'lolcat.png'; alert(outerScopeVar); var outerScopeVar; setTimeout(function() { outerScopeVar = 'Hello Asynchronous World!'; }, 0); alert(outerScopeVar); // Example using some jQuery var outerScopeVar; $.post('loldog', function(response) { outerScopeVar = response; }); alert(outerScopeVar); // Node.js example var outerScopeVar; fs.readFile('./catdog.html', function(err, data) […]

如何从asynchronous调用返回响应?

我有一个函数foo ,这使得一个Ajax请求。 我怎样才能返回foo的回应? 我尝试从successcallback中返回值,并将响应分配给函数内部的局部variables,并返回该variables,但是没有一个方法实际返回响应。 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`.