You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 00:50:37