简体   繁体   English

如何使用async / await获取第二个`then`回调参数?

[英]How to get the second `then` callback parameter with async/await?

For example 例如

randomLibPromise.then((data, err) => { // do something with err })

how would I translate that with await? 我怎么用等待翻译呢? This promise comes from a library so I don't have control over the fact that the error goes through then instead of catch . 这个承诺来自一个库,所以我无法控制错误通过then而不是catch的事实。 What I have is: 我有的是:

let data = await randomLibPromise.catch(err)

but I don't get that second parameter and I can't retrieve the error. 但我没有得到第二个参数,我无法检索错误。

Every example I find on Google talk about catch for error handling but not then . 我发现在谷歌的每个例子说说catch的错误处理,但不会then

To "fix" the weird promise, you could just throw err if there is one, and return the data otherwise: 为了“修复”这个奇怪的承诺,如果有的话你可以throw err ,否则return数据:

var fixed = randomLibPromise.then((data, err) => { 
    if(err) throw err;
    return data;
})

The result will be a promise which does the correct thing, ie passes the data to a then , an error to a catch or, if awaiting, either returns data or throws the error. 结果将是一个做出正确事情的承诺,即将数据传递给then ,将错误传递给catch或者,如果等待,则返回data或抛出错误。

fixed.then(data => { /* handle data */ }).catch(err => { /* handle err */ });
// or
try {
    var data = await fixed;
    // handle data
} catch(err) {
    //handle err
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM