相关疑难解决方法(0)

基本的Javascript承诺实现尝试

为了更好地理解promises如何在Javascript中工作,我决定尝试自己编写代码基本实现.

基本上我想实现Promises Object(我在代码中称之为Aaa),它将函数作为参数.此函数可以调用resolve对promise的解析,或拒绝reject它.基本实现和用法如下.根据承诺规范,不确定第二个参数是否可接受,但这是我到目前为止所得到的.

Aaa=function(f,pause) { 

    console.log("ggg");

    var t=this;
    this.f=f;
    this.thens=[];

    this.resolve=function(g) {

        for(var i=0;i<t.thens.length;i++)
        {
            // try/catch to be used later for dealing with exceptions

            try
            {
                t.thens[i].f(g);
                t.thens[i].resolve();
            }   
            catch(ex)
            {}

        }
    };  

    // to be implemented later
    this.reject=function(g) {};

    this.then=function(resolve,reject) {

        // i'm passing true for pause argument as we dont need to execute promise code just yet
        var nextPromise=new Aaa(resolve,true);

        this.thens.push(nextPromise);

        return nextPromise;
    }


    if(!pause)
        this.f(this.resolve,this.reject); 

}


var aaa=new Aaa(function(resolve,reject) {

    console.log("aaa");

    setTimeout(function() …
Run Code Online (Sandbox Code Playgroud)

javascript promise

58
推荐指数
2
解决办法
1万
查看次数

从setTimeout获取返回值

我只想从setTimeout获取返回值,但我得到的是函数的整个文本格式?

function x () {
    setTimeout(y = function () {
        return 'done';
    }, 1000);
    return y;
}

console.log(x());
Run Code Online (Sandbox Code Playgroud)

javascript return settimeout

51
推荐指数
3
解决办法
7万
查看次数

概念 - 提炼承诺如何运作?

我看过很多实现,它们看起来都很不一样,我无法真正提炼出承诺的本质.

如果我不得不猜测它只是一个在回调触发时运行的函数.

有人可以在几行代码中实现最基本的承诺.

例如,从这个答案

片段1

var a1 = getPromiseForAjaxResult(ressource1url);
a1.then(function(res) {
    append(res);
    return a2;
});
Run Code Online (Sandbox Code Playgroud)

如何传递函数以then了解何时运行.

也就是说,它如何传递回ajax在完成时触发的回调代码.

片段2

// generic ajax call with configuration information and callback function
ajax(config_info, function() {
    // ajax completed, callback is firing.
});
Run Code Online (Sandbox Code Playgroud)

这两个片段有何关联?

猜测:

// how to implement this

(function () {
    var publik = {};
        _private;
    publik.then = function(func){
        _private = func;
    };
    publik.getPromise = function(func){
        // ??
    };
    // ??
}())
Run Code Online (Sandbox Code Playgroud)

javascript

11
推荐指数
2
解决办法
3262
查看次数

标签 统计

javascript ×3

promise ×1

return ×1

settimeout ×1