admin管理员组文章数量:1302869
Is this code correct? Can I bine promises like that?
var data = {}
await getInfo(data)
.then(result => {data = result})
.catch(error => {})
doStuffOnlyAfterGetInfo(data)
Is this code correct? Can I bine promises like that?
var data = {}
await getInfo(data.)
.then(result => {data = result})
.catch(error => {})
doStuffOnlyAfterGetInfo(data)
Share
Improve this question
asked Feb 13, 2018 at 13:24
rendomrendom
3,7157 gold badges40 silver badges56 bronze badges
7
- why do you want to do this? – Amit Chauhan Commented Feb 13, 2018 at 13:27
- 2 Why not just try it? – Yury Tarabanko Commented Feb 13, 2018 at 13:27
- try { const data = await getInfo(data.) } catch(e) { } – Yurii Commented Feb 13, 2018 at 13:27
- 2 I'm doing it because I like it better than using try catch – rendom Commented Feb 13, 2018 at 13:29
-
4
If that is exactly your code, you can just write
const data = await getInfo(data2.).catch(() => {}); doStuffOnlyAfterGetInfo(data);
instead. – str Commented Feb 13, 2018 at 13:41
2 Answers
Reset to default 6Yes, you can do that, you can think of await
like this:
await x
where x
is a Promise OR any value. In your case that chain call returns a promise.
all of this works:
async function fn() {
try {
var a = await 20; // a = 20
var b = Promise.resolve(20); // b = 20
var c = Promise.reject(20); // This throws exception
var d = Promise.reject(20).catch(() => 30) // d = 30
var e = fetch(url) // same as fetch(url).then(e => /*...*/)
var f = fetch(url).then(res => res.json())
catch (e) {
console.log(e) // 20
}
}
Also don't forget, that you can only use await
in async
functions.
Seed the Docs
You can, since promise.then()
and promise.catch()
return promises as well.
You can do the same without then\catch
using try\catch
async function getInfo(url)
{
try{
const result = await fetch(url);
return {data: result};
}
catch(e){
}
}
本文标签: javascriptCombining classic promises with asyncStack Overflow
版权声明:本文标题:javascript - Combining classic promises with async - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741742788a2395359.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论