【问题标题】:how to return result value instead of promise?如何返回结果值而不是承诺?
【发布时间】:2019-04-17 02:47:50
【问题描述】:

我试图从 promise 中获取返回值,但我做不到。

我正在从 'react-native-sha256' 导入 { sha256 }

const sha256 = sha256(keytohash);
return sha256;

Promise {_40: 0, _65: 0, _55: null, _72: null}

我也试过了:

const sha256 = async () => {
const key = await sha256(keytohash).then(hash => (hash));
return key;
};

return sha256;

Promise {_40: 0, _65: 0, _55: null, _72: null}

有没有办法让我得到哈希值而不是 promise 对象?

【问题讨论】:

  • return JSON.stringfly(sha256);你能试试这个吗?
  • 从承诺中获得价值的方法是使用.then()。就是这样。您永远不能直接从异步操作中返回值。
  • @hongdevelop 不工作,结果如下:Promise {_40: 0, _65: 0, _55: null, _72: null} _40: 0 _55: "{"_40":0,"_65":0,"_55":null,"_72":null}" _65: 1 _72: null __proto__: Object

标签: react-native promise


【解决方案1】:

试试吧!

const getSha256 = async () => {
  const key = await sha256(keytohash)
  return key;
}

console.log(getSha256())

你返回的是异步函数而不是值。

Math.random = function
Math.random() = value

您需要使用 await 等待 promise.resolve。

【讨论】:

  • 不工作,它仍然会返回我的承诺对象
  • 你用过调试器吗?您可以通过在代码中编写“调试器”来停止代码。尝试 const getSha256 = async () => { const key = await sha256(keytohash) debbuger return key; }
  • 有什么不同?我得到的价值仍然是承诺对象
猜你喜欢
  • 2021-06-12
  • 1970-01-01
  • 2015-03-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-24
  • 2019-10-10
  • 2018-12-22
相关资源
最近更新 更多