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

JavaScript Async/Await执行顺序问题:代码输出不符求助

问题分析与代码修正

你的代码问题出在这几点:

  • function1 加了async但没正确返回异步结果:内部的setTimeout是独立异步操作,回调里的return不属于function1的返回值,导致function1实际返回的是一个状态为resolved但值为undefined的Promise,所以await后得到undefined。
  • 异步任务执行顺序:setTimeout属于宏任务,会等当前同步代码跑完才执行,所以先打印了result1: undefined,之后才触发setTimeout里的日志。
  • 还有个拼写错误:funtcion2应该是function2。

如果要得到你预期的输出顺序,需要调整日志位置并正确返回Promise,修正后的代码如下:

const function1 = async () => {
    // 用Promise包裹异步操作,正确返回结果
    return new Promise((resolve) => {
        setTimeout(() => {
            // 先把结果返回,再触发后续流程
            resolve('message');
        }, 500);
    });
};

const function2 = async () => {
    const result1 = await function1();
    // 拿到结果后先打印result1
    console.log('result1: ', result1);
    // 再打印完成提示
    console.log('function 1 finished');
};

function2();

执行后输出:

result1:  message
function 1 finished

如果一定要把function 1 finished的日志放在function1里,那输出顺序会是先打印完成提示再打印result1,代码如下:

const function1 = async () => {
    return new Promise((resolve) => {
        setTimeout(() => {
            console.log('function 1 finished');
            resolve('message');
        }, 500);
    });
};

const function2 = async () => {
    const result1 = await function1();
    console.log('result1: ', result1);
};

function2();

执行后输出:

function 1 finished
result1:  message

内容的提问来源于stack exchange,提问作者asounrb

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 00:55:54