相关疑难解决方法(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万
查看次数

ES5与ES6的承诺

我想知道JS承诺是否是es5的一部分?如果是这样,为什么它有时在旧版浏览器中不起作用,我们必须为它添加一个polyfill.另外,在这种情况下应该添加哪种polyfill,es5 one或es6?我对此有点困惑.

javascript promise es6-promise

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

使用promise的语法编写同步代码会有什么好处

是否存在同步承诺这样的概念?使用promises语法编写同步代码会有什么好处吗?

try {
  foo();
  bar(a, b);
  bam();
} catch(e) {
  handleError(e);
}
Run Code Online (Sandbox Code Playgroud)

...可以写成(但使用同步版本then);

foo()
  .then(bar.bind(a, b))
  .then(bam)
  .fail(handleError)
Run Code Online (Sandbox Code Playgroud)

javascript promise

8
推荐指数
1
解决办法
419
查看次数

在JavaScript中实现Promise类

我正在尝试用.then()javascript 实现具有可链接功能的简单promise类。这是我到目前为止所做的-

class APromise {
    constructor(Fn) {
        this.value = null;
        Fn(resolved => { this.value = resolved; });
    }
    then(fn) {
        fn(this.value);
        return this;
    }
}

function myFun() {
    return new APromise(resolve => {
        // just resolve('Hello'); works but this doesn't
        setTimeout(() => { resolve('Hello'); }, 2000);
    });
}

const log = v => { console.log(v); };

myFun().then(log).then(log);
Run Code Online (Sandbox Code Playgroud)

输出-

null
null
Run Code Online (Sandbox Code Playgroud)

Instead of 'Hello' 2 times. I think it is currently ignoring setTimeout() call, how should I make this …

javascript node.js promise ecmascript-6

1
推荐指数
1
解决办法
1489
查看次数

标签 统计

javascript ×4

promise ×4

ecmascript-6 ×1

es6-promise ×1

node.js ×1