【发布时间】:2019-01-02 07:11:53
【问题描述】:
我正在学习 Promise,并且我绝对想在继续之前确保我了解它们的用途。我正在使用一个用于在线服务的库,该库具有返回承诺的功能。
我阅读的几乎所有示例都使用链接的then() 函数中的解析数据
const result = Library.functionReturningAPromise()
result.then(function(res) {
const obj = new Example(res)
return obj
}).then(function(ob) {
// do the rest of the logic within these then() functions
})
或在async 函数中使用解析的数据
async function test() {
const result = await Library.functionReturningAPromise()
const obj = new Example(result)
// do the rest of the logic
}
我想知道是否有任何方法可以在“正常”同步代码中使用已解决的承诺中的数据
const result = Library.functionReturningAPromise()
// do something to resolve the promise
const obj = new Example(result)
或者,如果您需要始终“包装”所有您在 async 函数中使用已解决承诺中的数据的逻辑。
【问题讨论】:
-
“我想知道是否有任何方法可以在“正常”同步代码中使用已解决的承诺中的数据“没有。
-
不可能。无论您是否通过 Promise 访问结果都无所谓,当它异步可用时,这意味着它现在(同步)不可用 - 也不能 - 可用。
-
写
Library.functionReturningAPromise().then(...等会解决你的问题。您可以根据需要向 Promise 添加任意数量的“then”(或任何其他有效的)回调。 -
据我理解的问题,不是从异步函数中获取数据,而是在异步位之后处理数据。
.then-chaining 的异步方式和一般的编码风格如果你不习惯的话会让人感到困惑。即使你是,偶尔每个人都可能会迷失在一个.then太多:) -
不,但是从技术上讲,您不必等待承诺立即解决,您可以随时致电
then或catch(或async try/catch)承诺承诺,甚至多次并以不同的方式对其进行操作。
标签: javascript asynchronous promise synchronous