相关疑难解决方法(0)

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

我有一个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万
查看次数

如何将现有的回调API转换为承诺?

我想使用promises,但我有一个回调API,格式如下:

1. DOM加载或其他一次性事件:

window.onload; // set to callback
...
window.onload = function() {

};
Run Code Online (Sandbox Code Playgroud)

2.平原回调:

function request(onChangeHandler) {
    ...
}
request(function() {
    // change happened
    ...
});
Run Code Online (Sandbox Code Playgroud)

3.节点样式回调("nodeback"):

function getStuff(dat, callback) {
    ...
}
getStuff("dataParam", function(err, data) {
    ...
})
Run Code Online (Sandbox Code Playgroud)

4.具有节点样式回调的整个库:

API;
API.one(function(err, data) {
    API.two(function(err, data2) {
        API.three(function(err, data3) {
            ...
        });
    });
});
Run Code Online (Sandbox Code Playgroud)

如何在promises中使用API​​,我该如何"宣传"它?

javascript callback node.js promise bluebird

680
推荐指数
12
解决办法
20万
查看次数