async in constructor code example
Example 1: js class async constructor
function asyncRequest(id){
return new Paormise();
}
class MyClass {
constructor(name, age, cityId) {
(async function() {
this.name = name;
this.age = age;
this.city = await asyncRequest(cityId);
})();
}
}
Example 2: how to make an async function
function resolveAfter2Seconds() {
return new Promise(resolve => {
setTimeout(() => {
resolve('resolved');
}, 2000);
});
}
async function asyncCall() {
console.log('calling');
const result = await resolveAfter2Seconds();
console.log(result);
}
asyncCall();
Example 3: c# async constructor
public class ViewModel
{
public ObservableCollection<TData> Data { get; set; }
async public static Task<ViewModel> BuildViewModelAsync()
{
ObservableCollection<TData> tmpData = await GetDataTask();
return new ViewModel(tmpData);
}
private ViewModel(ObservableCollection<TData> Data)
{
this.Data = Data;
}
}
Example 4: c# async task constructor
Yes, they can, but they shouldn't.