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

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

问题描述

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

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?

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

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

而不是这个?

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

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

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

推荐答案

不,您不能像您在示例中建议的那样同步从承诺中获取数据.数据必须在回调函数中使用.或者,在函数式编程风格中,promise 数据可以map() 覆盖.

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.

如果您可以使用 async/await(您应该很棒),那么您可以编写看起来同步但保留承诺异步性的代码(见@loganfsmyth 评论).

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);

总的来说,因为您已经在使用 ES6,所以我假设您也在使用转译器.在这种情况下,您绝对应该尝试 async/await.请务必在决定中权衡,因为今天它们尚未获得批准的规范.

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天全站免登陆