如何从Promise中提取数据 [英] How to extract data out of a Promise

查看:3576
本文介绍了如何从Promise中提取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个返回数据的承诺,我希望将其保存在变量中。由于异步性质,这在JavaScript中是不可能的吗?我需要使用 onResolve 作为回调吗?



我可以以某种方式使用它(例如用async / await包装):

  const {foo,bar } = Promise.then(result => result.data,errorHandler); 
//脚本的其余部分

而不是这个?

  Promise.then(result => {
const {foo,bar} = result.data;
//脚本的其余部分
},errorHandler);

注意:使用Bluebird库而不是本机实现,我无法从Promise更改为asnyc / await或Generators。

解决方案

否则您无法从承诺中获取数据同步就像你在你的例子中建议的那样必须在回调函数中使用该数据。或者在函数式编程风格中,承诺数据可以是 map()ed。。 / p>

如果你可以使用 async / await (你应该这很棒)那么你可以编写看似同步的代码但保留一个承诺的异步性(参见@loganfsmyth评论)。

  const {foo,bar} = await iAmAPromise.then(result => result.data); 

总的来说,由于您已经在使用ES6,我假设您也在使用转换器。在这种情况下,你一定要尝试 async / await
只要确定在今天它们尚未批准的规范中做出决定。


I have a promise that returns data and I want to save that in variables. Is this impossible in JavaScript because of the async nature and do I need to use onResolve as a callback?

Can I somehow use this (e.g. wrap it with async/await):

const { foo, bar } = Promise.then(result => result.data, errorHandler);
// rest of script

instead of this?

Promise.then(result => {
   const { foo, bar } = result.data;
   // rest of script
 }, errorHandler);

Note: Bluebird library is used instead of native implementation, and I can't change from Promise to asnyc/await or Generators.

解决方案

NO you can't get the data synchronously out of a promise like you suggest in your example. The data must be used within a callback function. Alternatively in functional programming style the promise data could be map()ed over.

If your are OK using async/await (you should it's awesome) then you can write code that looks synchronous yet retain the asynchronicity of a promise (see @loganfsmyth comments).

const { foo, bar }  = await iAmAPromise.then(result => result.data);

Overall since you are already using ES6 I assume you are also using a transpiler. In which case you should definitely give async/await a try. Just be sure to weight in the decision that as today they are not yet a ratified specification.

这篇关于如何从Promise中提取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆