我已经使用 Promises 很长时间了,它们始终是我用来控制程序工作流的“东西”。示例:
Promise
.resolve(obj)
.then(doSomething1)
.then(doSomething2)
.catch(handleError)
现在,我想更改为 try-catch 样式,但我不知道什么才是正确的方法。
V1:
try {
var body = await Promise
.resolve(obj)
.then(doSomething1)
.then(doSomething2)
} catch (error) {
callback(error)
}
callback(null, {
statusCode: 200,
body
})
V2:
try {
var body = await Promise
.resolve(obj)
.then(doSomething1)
.then(doSomething2)
.then(body => {
callback(null, {
statusCode: 200,
body
})
})
} catch (error) {
callback(error)
}
什么是正确的方法?
最佳答案
您不必使用回调函数来切换到async
/await
。 async
函数只是一个 Promise 返回函数,而 await
是为了方便。所以你原来的功能的等价物很简单:
async function fn() {
try {
const obj = ...;
const result1 = await doSomething1(obj);
const result2 = await doSomething2(result1);
return result2;
} catch (err) {
return handleError(err);
}
}
如果您确实需要该回调:
async function fn(callback) {
try {
const obj = ...;
const result1 = await doSomething1(obj);
const result2 = await doSomething2(result1);
callback(null, result2);
} catch (err) {
callback(err);
}
}
关于javascript - 使用 await 而不是 Promises 的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47934806/