将Promise的回调定义为异步似乎存在一些固有的错误:
return new Promise(async (resolve,reject) => { const value = await somethingAsynchronous(); if (value === something) { return resolve('It worked!'); } else { return reject('Nope. Try again.'); } });
这显然是一个antipattern,并且有编码problems which can arise from it.我知道在这里捕获错误变得更容易,即使在try / catch块中放置await语句也是如此.
我的第一个问题是,当一个人想要转发具有不同解析/拒绝值的Promise时,最好的方法是什么?用then / catch?即
return new Promise((resolve,reject) => { somethingAsynchronous().then(value => { if (value === something) { return resolve('It worked!'); } else { return reject('Nope. Try again.'); } }); // errors would now be propagated up });
async function outerFunction() { const value = await somethingAsynchronous(); return new Promise((resolve,reject) => { if (value === something) { return resolve('It worked!'); } else { return reject('Nope. Try again.'); } }); }
但是如果在outerFunction()中有几个await语句,即调用多个异步函数的线性代码块,该怎么办呢?那么你每次都必须创建并返回一个新的Promise吗?
但那么你如何解释这样的代码呢?
async function outerFunction() { if (someSynchronousCheck()) { return 'Nope. Try again.' // another reject case } const value = await somethingAsynchronous(); // ... }
我觉得我让它变得比它应该更复杂.我试图避免嵌套回调/链接/ catch块而不会在将来产生更多问题.
我的最后一个问题是,为什么回调传递给Promise本身并不是异步?它已经包含在一个promise中,并期望异步调用resolve / reject函数.
解决方法
你做这个:
async function outerFunction() { const value = await somethingAsynchronous(); if (value === something) { return 'It Worked!'; } throw Error('Nope. Try again.'); }
使用async将outerFunction的结果包装为Promise.
如果您希望包装承诺解析为某些东西,只需从异步函数返回它.如果您希望拒绝包装承诺,请在异步函数内抛出错误.
But then how do you account for code such as this?
async function outerFunction() { if (someSynchronousCheck()) { throw Error('Nope. Try again.'); } const value = await somethingAsynchronous(); // ... }