Shivangi
Shivangi

Reputation: 93

How to use async/await instead of promises here

const Video = require("");
const token = "";
const connectOptions = {logLevel: "off"}
 
const startRoom = function(token) {
 console.log("hello world");
 Video.connect(a)
   .then(room => null
   })
   .catch(error => {
     console.log("error");
     return error
   });
}

The async/await will lead to removal of catch. Which is what I want to achieve.

Upvotes: 1

Views: 171

Answers (3)

codeGeek
codeGeek

Reputation: 1

or you can use this also..

async function startRoom(token) {
  console.log("hello world");
  try {
    let response = await fetch(token);
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    } else {
      let room = await video.connect(token, connectOptions);
      console.log("got a room");
    }
  } catch (e) {
    console.log(e);
  }
}

Upvotes: 0

David ZIP
David ZIP

Reputation: 162

Just wrap it in try-catch

const getRoom = async () => {
    try {
        const room = await Video.connect(token, connectOptions);
        console.log("got a room");
    } catch (e) {
        console.log("error");
    }
}

Upvotes: 0

TKoL
TKoL

Reputation: 13892

Just fyi, you're not using await INSTEAD of promises, you're using await WITH promises. async functions return promises, and await waits for promises to resolve

const Video = require("twilio-video");
const token = "test_token";
const connectOptions = {video: false, audio: false, logLevel: "off"}
 
const startRoom = async function(token) {
 console.log("hello world");
 try {
   const room = await Video.connect(token, connectOptions)
   console.log("got a room");
 } catch(error) {
   console.log("error");
 }
}

Upvotes: 1

Related Questions