繁体   English   中英

异步 function 调用在回调中未完成

[英]Async function call not complete in callback

我正在尝试使用一些异步函数,但我的代码,例如 this.saveAsCSV(lists,"lists.csv"); 似乎在 function 完成之前继续。 这不完全是我正在做的事情,但它是显示我的问题的缩短版本。 console.log(lists) 有正确的数据,但我认为它是在调用后评估的

   public render(): void {
    (async () => {  
      await this.GetListsBySiteID("6a368204-0534-4ffb-8014-157524ca9d50").then(lists => {
        console.log(lists);
        this.saveAsCSV(lists,"lists.csv");      
      });
    })();
  }

  async GetListsBySiteID(id:string):Promise<string[]>
  {
    let lists1:string[] = [];

    await pnp.sp.site.openWebById(id).then(result => 
    {
      result.web.lists.get().then(lists => 
      {
        lists.forEach(list => {
          lists1.push(list.Title);
        });      
      })
    });

    return lists;
  }

我该如何纠正?

该代码未经测试,但这是一个想法:

  1. GetListsBySiteID function 中返回 promise
  2. 填充lists值后解决 promise
GetListsBySiteID(id:string):Promise<string[]> {
  return new Promise((resolve, reject) => {
    try {
      let lists:string[] = [];
      pnp.sp.site.openWebById(id).then(result => 
      {
        result.web.lists.get().then(lists => 
        {
          lists.forEach(list => {
            lists.push(list.Title);
          });    

          resolve(lists);
        })
      });
    } catch (ex) {
      reject(ex);
    }
  );
}

这是因为在您的GetListsBySiteID() function 中有以下代码:

await pnp.sp.site.openWebById(id).then(result => 
{
  result.web.lists.get().then(lists => 
  {
    lists.forEach(list => {
      lists.push(list.Title);
    });      
  })
});

所以这里发生的是 JavaScript 正在await pnp.sp.site.openWebById(id) Promise 在继续之前完成。 您已附加.then()回调,因此它也正在await编辑。 现在问题出在您的.then()回调中:

您正在调用result.web.lists.get().then()但是这个 Promise 没有被await 解决方案是添加return关键字,如下所示:

await pnp.sp.site.openWebById(id).then(result => 
{
  return result.web.lists.get().then(lists =>  // <-- here I added return
  {
    lists.forEach(list => {
      lists.push(list.Title);
    });      
  })
});

所以现在await将导致 JavaScript 也等待嵌套的 Promise 。

这是此问题的完整异步/等待解决方案。 result.web.lists.get()上使用await将首先等待该过程完成,然后在解决后,最终为您提供正确的lists

public render(): void {
  (async() => {
    const lists = await this.GetListsBySiteID("6a368204-0534-4ffb-8014-157524ca9d50")
    console.log(lists);
    this.saveAsCSV(lists, "lists.csv");
  })();
}

async GetListsBySiteID(id:string):Promise<string[]> {
  let lists1: string[] = [];
  const result = await pnp.sp.site.openWebById(id)
  const lists = await result.web.lists.get()
  lists1 = lists.map(x => x.Title);
  return lists1;
}

请注意,在您的帖子中,您在GetListsBySiteID的末尾返回lists ,并且该变量未在 function 中定义。 所以,如果你想返回lists1而只是替换return lists; 带有return lists1; .

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM