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

如何确保代码等待getData()返回后再执行inquirer用户输入逻辑?

解决代码无法等待getData()响应的问题

要让代码正确等待getData()的响应,核心要确保两个关键点:

1. 保证getData()返回Promise对象

await关键字仅能作用于返回Promise的异步函数,如果getData()不是Promise-based的,await不会产生等待效果。

情况1:getData是回调式函数(比如基于传统AJAX或回调的API)

需要将其封装为Promise:

function getData() {
  return new Promise((resolve, reject) => {
    // 替换为你的实际接口请求逻辑
    fetch('你的endpoint地址')
      .then(response => {
        if (!response.ok) throw new Error('请求失败');
        return response.json();
      })
      .then(data => resolve(data))
      .catch(error => reject(error));
  });
}

情况2:getData使用axios等库

这类库本身返回Promise,直接返回即可:

async function getData() {
  const response = await axios.get('你的endpoint地址');
  return response.data;
}
// 或者非async写法
function getData() {
  return axios.get('你的endpoint地址').then(res => res.data);
}

2. 正确使用await并处理异常

在test函数中,确保await getData()执行完成后再继续逻辑,同时建议添加错误捕获避免Promise未处理的异常:

var test = async function() {
    try {
        // 等待getData()完成获取结果
        const result = await getData();
        console.log('接口返回数据:', result);
        
        // 等待用户按下回车后执行后续代码
        await getUserInputContinue();
        
        // 这里写用户确认后要执行的更多代码
        console.log('开始执行后续逻辑...');
    } catch (error) {
        console.error('获取数据失败:', error);
    }
}

额外注意事项

  • 如果你调用test()函数的地方也是同步环境,需要用.then()处理:
    test().catch(err => console.error(err));
    
  • 确保getUserInputContinue中的inquirer.prompt正确返回Promise(inquirer v8+的prompt方法本身返回Promise,无需额外处理)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 14:18:18