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

如何修改Promise返回值?TypeScript代码场景技术问询

问题与解决方案

问题背景

innerFunction()接受泛型类型参数并返回该类型的对象列表,现有代码如下:

type myType1 = [any[]];

type myType2 = {
    a: number;
};

type myType3 = {
    a: number;
    b?: number;
};

async function innerFunction<T>() {
    const r2: myType3 = {a:1, b:1}
    return [r2] as T[];
}

function outerFunction(): Promise<myType2[]> {
    let x = innerFunction<myType3>();
    return x
}

console.log("outerFunction() = ", outerFunction())

运行输出:

outerFunction() =  Promise { [ { a: 1, b: 1 } ] }

需求是在outerFunction()中修改返回数据的值,但不知道如何访问Promise x内部的实际值。


解决方案

由于innerFunction是异步函数,返回的是Promise对象,无法直接同步读取内部值,必须通过异步方式处理,以下两种方法都可行:

方法1:使用async/await(代码更简洁直观)

将outerFunction改为异步函数,通过await获取Promise的结果后修改:

type myType1 = [any[]];

type myType2 = {
    a: number;
};

type myType3 = {
    a: number;
    b?: number;
};

async function innerFunction<T>() {
    const r2: myType3 = {a:1, b:1}
    return [r2] as T[];
}

async function outerFunction(): Promise<myType2[]> {
    // 用await获取Promise内部的数组数据
    const data = await innerFunction<myType3>();
    
    // 按需修改数据,示例:修改a值并删除b属性以匹配myType2结构
    data.forEach(item => {
        item.a = 2; // 修改a的值
        delete item.b; // 可选:严格符合myType2类型时删除多余属性
    });
    
    return data;
}

// 调用异步函数需用.then()或await
outerFunction().then(result => {
    console.log("outerFunction() = ", result);
});

方法2:使用Promise的.then()链式调用

如果不想修改outerFunction的异步状态,可通过.then()处理Promise结果:

type myType1 = [any[]];

type myType2 = {
    a: number;
};

type myType3 = {
    a: number;
    b?: number;
};

async function innerFunction<T>() {
    const r2: myType3 = {a:1, b:1}
    return [r2] as T[];
}

function outerFunction(): Promise<myType2[]> {
    return innerFunction<myType3>().then(data => {
        // 在回调中修改数据
        data.forEach(item => {
            item.a = 3;
            delete item.b;
        });
        return data;
    });
}

outerFunction().then(result => {
    console.log("outerFunction() = ", result);
});

关键说明

  • Promise是异步操作的封装,必须通过await(仅能在async函数内使用)或.then()回调才能获取内部的实际值。
  • 若需要返回值严格匹配myType2[]类型,建议删除b属性;TypeScript默认允许对象存在额外属性,但严格场景下需做清理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 09:02:32