myo*_*yol 5 javascript asynchronous synchronous 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
})
Run Code Online (Sandbox Code Playgroud)
或在async函数中使用解析的数据
async function test() {
const result = await Library.functionReturningAPromise()
const obj = new Example(result)
// do the rest of the logic
}
Run Code Online (Sandbox Code Playgroud)
我想知道是否有任何方法可以使用“正常”同步代码中已解决的承诺中的数据
const result = Library.functionReturningAPromise()
// do something to resolve the promise
const obj = new Example(result)
Run Code Online (Sandbox Code Playgroud)
或者,如果您需要始终“包装” 使用函数中已解决的承诺中的数据的所有逻辑async。
我想知道是否有任何方法可以在“正常”同步代码中使用已解决的承诺中的数据
在处理异步响应时,没有办法编写完全同步的代码。一旦任何操作是异步的,您就必须使用异步技术处理响应,并且不能同步编程。你必须学会异步编程。
您显示的两个选项 (.then()或async/await) 是处理返回的承诺的两个选择。
或者,如果您需要始终“包装”所有使用异步函数中已解析承诺中的数据的逻辑。
如果你想使用await这样你就可以编写看起来同步的代码来处理承诺,那么所有这些代码都必须在一个async函数中。而且,一旦您离开该函数的作用域(例如想要返回一个值),您就会从该async函数返回一个承诺,并且必须再次处理该承诺。
没有办法解决这个问题。这只是人们必须在 Javascript 中学习的东西。一段时间后,它变成了第二天性。
正如您似乎知道的那样,您可以使用async和await来获得一些看起来同步的逻辑流,但是在执行此操作时,需要确保您理解一些事情。从你的例子:
async function test() {
const result = await Library.functionReturningAPromise()
const obj = new Example(result);
// do the rest of the logic
}
Run Code Online (Sandbox Code Playgroud)
async返回一个承诺。这是你从他们那里得到的唯一一种返回值。如果来访者寻找一个返回值或想知道当异步操作完成或正在寻找错误,他们必须使用与返回的承诺.then(),.catch()一次,或与await内部async功能。await并且需要在本地处理拒绝,那么您需要将它们包装起来try/catch(与同步异常的语法非常相似)。下面是使用try/catchwithawait在本地处理错误的示例:
async function test() {
try {
const result = await Library.functionReturningAPromise();
const obj = new Example(result);
// do the rest of the logic
} catch(e) {
// handle promise rejection here
}
}
Run Code Online (Sandbox Code Playgroud)
下面是调用者处理错误的示例:
async function test() {
const result = await Library.functionReturningAPromise();
const obj = new Example(result);
// do the rest of the logic
}
test().then(() => {
console.log("all done");
}).catch(err => {
console.log(err);
});
Run Code Online (Sandbox Code Playgroud)