How to extract data out of a Promise

前端 未结 2 848
庸人自扰
庸人自扰 2020-12-08 20:29

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

2条回答
  •  生来不讨喜
    2020-12-08 21:11

    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.

提交回复
热议问题