相关疑难解决方法(0)

为什么javascript ES6 Promises在解决后会继续执行?

据我所知,promise是可以解决()或拒绝()但我很惊讶发现在调用解析或拒绝后,promise中的代码继续执行.

我认为解决或拒绝是退出或返回的异步友好版本,这将停止所有立即执行功能.

有人可以解释为什么以下示例有时会在解析调用后显示console.log的想法:

var call = function() {
    return new Promise(function(resolve, reject) {
        resolve();
        console.log("Doing more stuff, should not be visible after a resolve!");
    });
};

call().then(function() {
    console.log("resolved");
});
Run Code Online (Sandbox Code Playgroud)

jsbin

javascript promise ecmascript-6 es6-promise

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

基本的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万
查看次数

标签 统计

javascript ×2

promise ×2

ecmascript-6 ×1

es6-promise ×1