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
 |  Show 2 more ments

2 Answers 2

Reset to default 6

Yes, 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