【问题标题】:Returning data from promise to a variable using map使用map将数据从promise返回到变量
【发布时间】:2022-01-21 17:36:47
【问题描述】:

我想将数据返回给一个变量。 我已经解决了承诺并将其打印到控制台。我希望数据应该可以在外部访问并且可以被变量使用。 我想要 console.log(x) 中的任何值,应该在变量的循环之外(比如变量名 z)

 var libobj =await service.getdata(); //----------> returning from service file and libobj is returning  promise (fullfilled)

// var z; -----Data needed here or below the map loop

libobj.map( (res: any) => 
(res.then((x : any )=>console.log(x)) )); //--------> console .log(x) printing all  the data needed

【问题讨论】:

  • 不知道 "getdata()" 返回什么,但是如果是 fetch 调用它需要是 "libobj.json()"
  • libobj 的类型是什么?它是一系列承诺吗?
  • @JafarJabr - 获取数据返回承诺
  • @NalinRanjan 是的,它是一系列承诺
  • 检查Promise.all

标签: javascript typescript async-await promise


【解决方案1】:

以下是展示Promise.all的示例...

let createAPromise = (x) => new Promise((res, rej) => setTimeout(() => { console.log(`Resolving ${x}`); res(x)}, x));


async function test() {

  const libobj = [300, 500, 700].map(x => createAPromise(x));

  const values = await Promise.all(libobj);

  console.log('Resolved all with', values);
}

test();

这个例子只是为了强调Promise.all从promise集合中获取最终值的一种方式...

【讨论】:

  • 我回复了您的评论(我没有注意到您的回答)。我试图说明的一点是,从.then 回调分配一个外部值是行不通的,但我看到你的答案没有这个问题。 :) letconst 在这里没什么区别。
猜你喜欢
  • 2017-11-16
  • 2018-04-07
  • 1970-01-01
  • 2018-06-05
  • 2017-03-03
  • 1970-01-01
  • 2016-04-27
  • 2017-01-16
  • 2021-03-17
相关资源
最近更新 更多