为了更好地理解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) 我有一个简单的代码,除了Internet Explorer 11之外,在每个浏览器上运行都很完美.如何让它在所有浏览器上运行?
提前致谢.
'use strict';
let promise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("result");
}, 1000);
});
promise
.then(
result => {
alert("Fulfilled: " + result);
},
error => {
alert("Rejected: " + error);
}
);
Run Code Online (Sandbox Code Playgroud)