什么'我的javascript promise代码有问题
what's wrong with my javascript promise code
我想自己实现一个javascript promise来理解机制,这是我的代码,但它报告了未定义的错误,有人能帮我看看吗?
var Promise = function(){
this.successesCallback = [];
}
Promise.prototype.then = function(success){
console.log("add success");
this.successesCallback.push(success);
}
var Defer = function(){
this.promise = new Promise();
}
Defer.prototype.resolve = function(){
console.log("defer resolve is calling");
console.log("2promise of defer:" + this.promise)
this.promise.successesCallback[0]();
}
var remoteCall = function(callBack){
for(var i = 0; i < 1000000000; i++){
}
callBack();
}
var callRemote = function(){
var defer = new Defer();
console.log("promise of defer:" + defer.promise)
console.log("set timer for remote call");
setTimeout(function(){remoteCall(defer.resolve)}, 0);
console.log("remote call is triggered");
return defer.promise;
}
callRemote().then(function(){console.log("Hello, server call done")});
您可以通过节点运行
您在setTimeout()
回调中丢失了defer
和resolve()
之间的绑定。
一种解决方案是使用bind()
:
setTimeout(function(){remoteCall(defer.resolve.bind( defer )}, 0);
您在setTimeout()
回调中丢失了defer
和resolve()
之间的绑定,如另一个答案中所述。现在您可以使用()=>
而不是function()
来维护ES6之后的当前绑定。
setTimeout(()=>{remoteCall(defer.resolve)}, 0);
相关文章:
- 使用Promise来创建“;原子“;Javascript中的代码块
- 以惯用方式组织javascript webdriver promise代码
- Node.js Promise - 代码不应该等到 .then 完成()
- Promise处理程序中的同步代码
- 等待promise解析后再执行代码
- 如何重写这段代码,使执行不必从Javascript Promise.then()方法开始
- 如何使EXPECT条件等待promise被解析(代码封装在方法中)
- 如何使用 Jest 编写单元测试,用于 Promise 的代码
- JavaScript 中的 promise 干预其余代码
- 什么'我的javascript promise代码有问题
- 如何让promise对象成功函数中的代码在调用后的代码之前执行
- 在解析云代码中使用自己的promise
- 在promise中包装整个代码块时,promise和deferred之间的区别
- 拒绝promise时停止代码执行
- 如何在云代码中使用Parse promise进行循环查询
- 在angular js promise中未获取状态错误代码
- 如何正确使用promise,使我的代码;不要这么嵌套
- 如何处理Parse promise错误,使它们不会'不要一直执行代码
- 将节点异步代码转换为promise
- 为什么不't运行此promise调用之后的代码