Defining async function inside promise

Viewed 10191

I am writing code for promises using .then. Now, I have decided to write it using await/async. I have called a function add_Lessons inside promise and then call another function in .then of that function. Here is my code using .then.

function create_section(sections,course_ID,i) {
return new Promise(
    (resolve) => {
        var s_duration = 0;
        var sname = sections[i].name;
        var s_obj = {
            //some object;
        }
        var section_id;
        DB.section.create(s_obj,function (err, data_s) 
        {
            if (err) return next(err);
            section_id = data_s._id;
            var lesson = sections[i].lessons;
            add_lessons(lesson,section_id,i)
            .then(function(arr){
                resolve(arr);
            })
        });
    }
);
};

This is the code using await/async.

function create_section(sections,course_ID,i) {
return new Promise(
    async function resolve() {
        var s_duration = 0;
        var sname = sections[i].name;
        var s_obj = {
           //some obj
        }
        var section_id;
        DB.section.create(s_obj,function (err, data_s) 
        {
            if (err) return next(err);
            section_id = data_s._id;
            var lesson = sections[i].lessons;
            var arr = await add_lessons(lesson,section_id,i)
            resolve(arr);
        });
    }
);
};

The code using await/async shows an error that add_lessons is unexpected identifier. So tell me how to define async function inside promise?

2 Answers
const getData = new Promise(async (res, rej) => {
    try {
      const response = await fetch("https://jsonplaceholder.typicode.co2m/todos/1");
      if (!response.ok) {
        return rej("Error while fetch");
      }
      const data = await response.json();
      return res(data);
    } catch (error) {
      return rej(error);
    } 
});

getData
.then(data=>console.log(data))
.catch(err=>console.log(err));
Related