【问题标题】:Custom fetch() not working in Office Add-in自定义 fetch() 在 Office 加载项中不起作用
【发布时间】:2021-12-11 01:50:59
【问题描述】:

我有以下自定义函数要获取

function myfunction(){
  fetch('https://api.jokes.one/jod?category=animal')
  .then((response) => {
    return response.json();
  })
  .then((myJson) => {
    return JSON.stringify(myJson);
  });
}

获取数据后,我希望将它们插入到word文档中:

export async function run() {
  return Word.run(async (context) => {

    var a = myfunction();

    const paragraph = context.document.body.insertParagraph(a, Word.InsertLocation.end);

    await context.sync();
  });
}

但是当我尝试启动开发服务器运行代码时,word文档中没有插入任何数据。有什么我错过的吗?我怀疑这是一些像 CORS 一样的配置设置(我不太清楚为什么)。如果有详细的解释就好了谢谢

【问题讨论】:

  • 尝试使用async 关键字定义myFunction。然后将var a = myfunction(); 替换为var a = await myfunction();。
  • 是的,现在可以使用了
  • 好的。我会把这个作为答案。请接受它,以便它在 Stack 的统计信息中被视为已回答。

标签: node.js office365 office-js office-addins


【解决方案1】:

当后面的代码行运行时,您的 myfunction() 不完整。需要加上await关键字,这样下一行代码就等到函数完成了,像这样:

var a = await myfunction();

另外,您需要使用async 关键字定义myfunction(),以便您可以等待它。

【讨论】:

    【解决方案2】:

    response.json() 更依赖于一个 promise 结构,所以你必须再次调用 then。

    function myfunction(){
      fetch('https://api.jokes.one/jod?category=animal')
      .then((response) => {
        response.json().then(result => {
        return result;
        })      
      })
    }
    

    【讨论】:

      猜你喜欢
      • 2012-12-01
      • 1970-01-01
      • 2020-05-03
      • 1970-01-01
      • 1970-01-01
      • 2018-06-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多