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

如何修改JavaScript代码,返回包含指定数据的已解析Promise

解决方案

首先要明确:async 函数本身会自动返回一个 Promise,完全不需要手动创建新的 Promise 实例。你的代码可以大幅简化:

修改后的最终代码:

const getText = async () => {
  const TheData = await getDataSet('City', 'New York'); // {country:'USA',city:'New York'}
  const TheText = TheData['country']; // 'USA'
  return TheText; // 返回值会自动被包装为已解析状态的Promise
};

调用方式保持你的需求逻辑即可:

getText().then(result => alert(result)); // 会弹出'USA'

为什么不需要手动创建Promise?

你之前写的new Promise逻辑完全多余——await getDataSet(...)已经完成了异步等待,拿到TheText后,async函数在返回这个值时,JavaScript引擎会自动把它包装成一个已解析状态的Promise,不需要额外写监听onsuccess的冗余代码。

如果需要处理查询失败的场景,只需要用try/catch捕获错误,或者在调用时通过.catch()处理:

const getText = async () => {
  try {
    const TheData = await getDataSet('City', 'New York');
    return TheData['country'];
  } catch (error) {
    // 捕获getDataSet的调用错误,比如数据库查询失败
    throw new Error('城市数据查询失败:' + error.message);
  }
};

// 调用时处理错误
getText()
  .then(result => alert(result))
  .catch(err => console.error(err));

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 04:22:32