【发布时间】:2019-05-06 23:15:33
【问题描述】:
您好,我是 javascript 新手,最近一直在学习 Promise。在继续我的逻辑之前,我试图等待网络调用的结果。为此,我认为我需要一个等待网络调用结果的承诺。我一直在练习承诺,并注意到一些我不理解的行为。
var mybool = false;
// Promise
var mypromise = new Promise(
function (resolve, reject) {
if (mybool) {
var pvalue = 'PASS';
resolve(pvalue);
} else {
var fvalue = new Error('FAIL');
reject(fvalue);
}
}
);
// call promise
var callpromise = function () {
mypromise
.then(function (fulfilled) {
// yay, you got a new phone
console.log(fulfilled);
})
.catch(function (error) {
// ops, mom don't buy it
console.log(error.message);
});
}
callpromise();
console.log('This will appear first since prev function call is still thinking');
mybool = true;
console.log(mybool);
callpromise();
如您所见,var mybool 决定了 promise 函数的输出。当我运行这个程序时,这是输出:
"This will appear first since prev function call is still thinking"
true
"FAIL"
"FAIL"
有人可以解释为什么即使在翻转mybool var 之后,2ndcallpromise() 仍然输出我只能从mybool = false 得到的值吗?
【问题讨论】:
-
作为其他在 HTTP 请求中苦苦挣扎的人的旁注,内置的
XMLHttpRequest有一个易于使用的异步/同步切换参数,您可以翻转而不是弄乱您自己的自定义承诺链.request.open('GET', 'https://ghibliapi.herokuapp.com/films', true)^ asyncrequest.open('GET', 'https://ghibliapi.herokuapp.com/films', false)^ synchronus(IE 线程在此 HTTP 请求通过/失败之前不会继续)