我正在使用編寫承諾代碼,然後。現在,我決定使用await/async編寫它。我已經調用函數add_Lessons內部承諾,然後調用另一個函數在,然後該功能。這裏是我的代碼,使用,然後。定義承諾內的異步函數
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);
})
});
}
);
};
這是使用等待/異步的代碼。
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);
});
}
);
};
使用await/async的代碼顯示add_lessons是意外標識符的錯誤。 那麼告訴我如何在promise中定義異步函數?
避免['Promise' constructor antipattern](https://stackoverflow.com/q/23803743/1048572?What-is-the-promise-construction-antipattern-and-how-to-avoid-it)! – Bergi