Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining classic promises with async

Is this code correct? Can I combine promises like that?

var data = {}
await getInfo(data.com)
 .then(result => {data = result})
 .catch(error => {})
doStuffOnlyAfterGetInfo(data)
like image 912
rendom Avatar asked Feb 13 '18 13:02

rendom


2 Answers

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

like image 199
notgiorgi Avatar answered Oct 10 '22 00:10

notgiorgi


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){

   }
}
like image 36
Amir Popovich Avatar answered Oct 09 '22 22:10

Amir Popovich