我正在尝试从头开始创建一个简单的自定义承诺。
由于某种原因,在调用then之前正在执行。onResolve function因此,该response变量是一个空字符串。我这里哪里出错了?
索引.js
import CustomPromise from "./customPromise";
const makeApiCall = () => {
return new CustomPromise((success, failure) => {
setTimeout(() => {
let apiResponse = { statusCode: 200, response: "hello" };
if (apiResponse.statusCode == 200) {
success(apiResponse);
} else {
failure(apiResponse);
}
}, 1000);
});
};
makeApiCall().then(response => {
console.log(response);
});
CustomPromise.js
export default class CustomPromise {
constructor(executorFunc) {
this.onResolve = this.onResolve.bind(this);
this.onReject = this.onReject.bind(this);
this.response = "";
executorFunc(this.onResolve, this.onReject);
}
then(input) {
input(this.response);
}
onResolve(response) {
this.response = response;
}
onReject(input) {
input();
}
}
SMILET
相关分类