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

如何从异步函数中返回Fetch API的请求结果?

解决异步函数无法返回API请求结果的问题

你的核心问题在于异步函数的返回值处理错误,以及没有正确传递异步操作的结果。下面一步步拆解问题并给出解决方案:

问题分析

  1. 当前callRelation函数内部定义了一个立即执行的异步函数(IIFE),但外层函数没有返回这个IIFE的结果,导致callRelation默认返回undefined,这就是console.log(test)输出undefined的原因。
  2. 异步操作本身是异步执行的,直接赋值变量无法拿到最终结果,必须等待异步操作完成后再获取值。

修改后的代码(推荐用async/await)

直接把callRelation声明为异步函数,去掉内部的IIFE,逻辑更清晰:

async function callRelation(id) {
    const api = await fetch(
        "https://www.overpass-api.de/api/interpreter?",
        {
            method: "POST",
            headers: {
                Accept: "application/json",
                "Content-Type": "application/json",
            },
            body: "[out:json];rel(" + id + ");(._;>;);out;",
        },
    );

    const request = await api.json();
    const path = [];

    for (const pair of request.elements) {
        if (pair.type === "node") {
            path.push([pair.lat, pair.lon]);
        }    
    }
    return path;
}

正确调用方式

因为async函数返回的是Promise对象,必须通过以下两种方式获取结果:

方式1:用async/await(需在异步环境中调用)

async function handlePath() {
    const test = await callRelation(10000);
    console.log(test);
    // 在这里用test执行后续操作
}
handlePath();

方式2:用.then()回调

callRelation(10000).then(test => {
    console.log(test);
    // 在这里用test执行后续操作
});

关于你尝试的Callback写法

如果要用Callback,需要把回调函数放在异步操作完成后调用,正确写法如下(但async/await更易读):

function callRelation(id, callback) {
    fetch(
        "https://www.overpass-api.de/api/interpreter?",
        {
            method: "POST",
            headers: {
                Accept: "application/json",
                "Content-Type": "application/json",
            },
            body: "[out:json];rel(" + id + ");(._;>;);out;",
        },
    )
    .then(api => api.json())
    .then(request => {
        const path = [];
        for (const pair of request.elements) {
            if (pair.type === "node") {
                path.push([pair.lat, pair.lon]);
            }    
        }
        callback(path);
    });
}

// 调用
callRelation(10000, function(test) {
    console.log(test);
    // 后续操作写在这里
});

关键要点

  • 异步函数的返回值是Promise,不能直接同步获取,必须用await或.then()等待结果
  • 避免在同步函数中直接调用异步函数并赋值,因为异步操作还未完成时变量值还没生成
  • async/await是处理异步流程的现代方式,比嵌套回调更易维护

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 14:50:19