标签: asynchronous

如何从异步调用返回响应?

我有一个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)

javascript ajax jquery asynchronous xmlhttprequest

5208
推荐指数
38
解决办法
134万
查看次数

如何异步上传文件?

我想用jQuery异步上传一个文件.这是我的HTML:

<span>File</span>
<input type="file" id="file" name="file" size="10"/>
<input id="uploadbutton" type="button" value="Upload"/>
Run Code Online (Sandbox Code Playgroud)

在这里我的__CODE__代码:

$(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: ");
            }
        });
    });
});
Run Code Online (Sandbox Code Playgroud)

我只获取文件名,而不是上传文件.我该怎么做才能解决这个问题?

现行解决方案

我正在使用jQuery Form Plugin上传文件.

javascript ajax jquery asynchronous xmlhttprequest

2841
推荐指数
28
解决办法
129万
查看次数

如何让jQuery执行同步而非异步的Ajax请求?

我有一个JavaScript小部件,它提供标准的扩展点.其中之一就是beforecreate功能.它应该返回false以防止创建项目.

我使用jQuery在这个函数中添加了一个Ajax调用:

beforecreate: function (node, targetNode, type, to) {
  jQuery.get('http://example.com/catalog/create/' + targetNode.id + '?name=' + encode(to.inp[0].value),

  function (result) {
    if (result.isOk == false) 
        alert(result.message);
  });
}
Run Code Online (Sandbox Code Playgroud)

但我想阻止我的小部件创建项目,所以我应该返回false母函数,而不是回调.有没有办法使用jQuery或任何其他浏览器中的API执行同步AJAX请求?

javascript ajax jquery asynchronous

1173
推荐指数
13
解决办法
69万
查看次数

1126
推荐指数
17
解决办法
84万
查看次数

如何以及何时使用'async'和'await'

从我的理解主要事情之一asyncawait要做的就是让代码易于读写-但使用它们等于产卵后台线程来执行持续时间长的逻辑?

我正在尝试最基本的例子.我在内联添加了一些评论.你能为我澄清一下吗?

// I don't understand why this method must be marked as `async`.
private async void button1_Click(object sender, EventArgs e)
{
    Task<int> access = DoSomethingAsync();
    // task independent stuff here

    // this line is reached after the 5 seconds sleep from 
    // DoSomethingAsync() method. Shouldn't it be reached immediately? 
    int a = 1; 

    // from my understanding the waiting should be done here.
    int x = await access; 
}

async Task<int> DoSomethingAsync()
{
    // is …
Run Code Online (Sandbox Code Playgroud)

.net c# asynchronous async-await

989
推荐指数
19
解决办法
78万
查看次数

为什么我的变量在函数内部修改后没有改变? - 异步代码引用

鉴于以下示例,为什么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)

javascript asynchronous

675
推荐指数
6
解决办法
18万
查看次数

如何检查Android上的互联网访问?InetAddress永远不会超时

我有一个AsyncTask应该检查网络访问主机名.但是doInBackground()永远不会超时.有人有线索吗?

public class HostAvailabilityTask extends AsyncTask<String, Void, Boolean> {

    private Main main;

    public HostAvailabilityTask(Main main) {
        this.main = main;
    }

    protected Boolean doInBackground(String... params) {
        Main.Log("doInBackground() isHostAvailable():"+params[0]);

        try {
            return InetAddress.getByName(params[0]).isReachable(30); 
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;       
    }

    protected void onPostExecute(Boolean... result) {
        Main.Log("onPostExecute()");

        if(result[0] == false) {
            main.setContentView(R.layout.splash);
            return;
        }

        main.continueAfterHostCheck();
    }   
}
Run Code Online (Sandbox Code Playgroud)

networking android asynchronous

637
推荐指数
27
解决办法
45万
查看次数

如何同步运行异步Task <T>方法?

我正在学习async/await,并遇到了需要同步调用异步方法的情况.我怎样才能做到这一点?

异步方法:

public async Task<Customers> GetCustomers()
{
    return await Service.GetCustomersAsync();
}
Run Code Online (Sandbox Code Playgroud)

正常使用:

public async void GetCustomers()
{
    customerList = await GetCustomers();
}
Run Code Online (Sandbox Code Playgroud)

我尝试过使用以下内容:

Task<Customer> task = GetCustomers();
task.Wait()

Task<Customer> task = GetCustomers();
task.RunSynchronously();

Task<Customer> task = GetCustomers();
while(task.Status != TaskStatus.RanToCompletion)
Run Code Online (Sandbox Code Playgroud)

我也从这里尝试了一个建议,但是当调度程序处于暂停状态时它不起作用.

public static void WaitWithPumping(this Task task) 
{
        if (task == null) throw new ArgumentNullException(“task”);
        var nestedFrame = new DispatcherFrame();
        task.ContinueWith(_ => nestedFrame.Continue = false);
        Dispatcher.PushFrame(nestedFrame);
        task.Wait();
}
Run Code Online (Sandbox Code Playgroud)

以下是调用的异常和堆栈跟踪RunSynchronously:

System.InvalidOperationException

消息:可能无法在未绑定到委托的任务上调用RunSynchronously.

InnerException:null

资料来源:mscorlib …

c# asynchronous async-await c#-5.0

606
推荐指数
16
解决办法
36万
查看次数

为什么我们需要Redux中的异步流中间件?

根据文档,"没有中间件,Redux商店只支持同步数据流".我不明白为什么会这样.为什么容器组件不能调用异步API,然后调用dispatch操作?

例如,想象一个简单的UI:字段和按钮.当用户按下按钮时,该字段将填充来自远程服务器的数据.

一个字段和一个按钮

import * as React from 'react';
import * as Redux from 'redux';
import { Provider, connect } from 'react-redux';

const ActionTypes = {
    STARTED_UPDATING: 'STARTED_UPDATING',
    UPDATED: 'UPDATED'
};

class AsyncApi {
    static getFieldValue() {
        const promise = new Promise((resolve) => {
            setTimeout(() => {
                resolve(Math.floor(Math.random() * 100));
            }, 1000);
        });
        return promise;
    }
}

class App extends React.Component {
    render() {
        return (
            <div>
                <input value={this.props.field}/>
                <button disabled={this.props.isWaiting} onClick={this.props.update}>Fetch</button>
                {this.props.isWaiting && <div>Waiting...</div>}
            </div>
        ); …
Run Code Online (Sandbox Code Playgroud)

javascript asynchronous reactjs redux redux-thunk

600
推荐指数
9
解决办法
12万
查看次数

Akka的好用例

我听说过很多关于Akka框架(Java/Scala服务平台)的狂热,但到目前为止还没有看到很多用例的实际例子.所以我有兴趣听听开发人员成功使用它的事情.

只有一个限制:请不要包括编写聊天服务器的情况.(为什么?因为这被过度使用作为许多类似事物的一个例子)

java asynchronous scala use-case akka

596
推荐指数
12
解决办法
17万
查看次数