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

使用async-await调用REST接口返回数组,取首元素得undefined问题

问题原因与解决方案

核心问题:运算符优先级

你碰到的问题是运算符优先级搞的鬼:await的优先级比数组索引[]低,代码执行时会先调用saveProduct(product)拿到一个Promise<Product[]>,接着直接去取这个Promise对象的[0]属性——但Promise本身根本没有这个属性,结果自然是undefined。

验证逻辑

你可以简单测试下这个执行顺序:

const promise = this._productService.saveProduct(product);
console.log(promise[0]); // 输出undefined,因为Promise对象没有[0]属性
const result = await promise;
console.log(result[0]); // 输出正确的Product对象

正确写法

要是想一行完成提取,得用括号把await调用包起来,提升它的优先级:

const newProduct: Product = (await this._productService.saveProduct(product))[0];
console.log(newProduct); // 正常打印产品对象

或者保持分步写法,先await拿到完整数组再提取元素,这种方式也更清晰易懂:

const newProductArray: Product[] = await this._productService.saveProduct(product);
const newProduct: Product = newProductArray[0];
console.log(newProduct);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 11:49:54