为何Promise未等待异步代码执行?新手的Promise困惑求解
关于Promise的用法与实用价值的疑惑
我刚接触Promise,正试图理解它的用法。W3Schools上有一篇介绍Promise的页面,给出了如下示例代码:
let myPromise = new Promise(function(myResolve, myReject) { let x = 0; // The producing code (this may take some time) if (x == 0) { myResolve("OK"); } else { myReject("Error"); } }); myPromise.then( function(value) {myDisplayer(value);}, function(error) {myDisplayer(error);} );
我尝试自己编写代码,写出了如下版本:
let p = new Promise(function test(resolve, reject){ // here is supposed to be where the async code takes place, according to the // article. let a = 0; setTimeout(() => {a = Math.floor(Math.random()*6)}, "1000") // ...however the condition triggers before the setTimeout takes place. if(a >= 0) { resolve(`Success ! a = ${a}`); } else { reject(`Failure ! a = ${a}`); } }); p.then(function logResult(result){ console.log(result); })
但发现判断逻辑在setTimeout执行前就触发了,于是我调整为如下代码:
let q = new Promise(function test(resolve, reject){ let a = 0; setTimeout(() => { a = Math.floor(Math.random()*6); if(a >= 4) { resolve(`Success ! a = ${a}`); } else { reject(`Failure ! a = ${a}`); } }, "1000") }); q.then(function logResult(result){ console.log(result); })
这段代码能正常运行,但所有逻辑都由setTimeout的回调处理,不用Promise也能实现同样效果:
let a = 0; setTimeout(() => { a = Math.floor(Math.random() * 6); if (a >= 4) { console.log(`Success ! a = ${a}`); } else { console.log(`Failure ! a = ${a}`); } }, "1000")
我显然对Promise处理异步代码的方式及其实用价值存在误解,希望有人能为我解惑。
内容的提问来源于stack exchange,提问作者Nono Nunu
相关产品推荐
相关产品推荐

