在以下代码中,return
不返回等待的值。我怎样才能使诺言在返回之前得到解决。因此,我希望result
成为SUCCESS
而不是承诺。
const foo = async()=>{
try{
let a = await new Promise((resolve)=>{
resolve('SUCCESS')
})
console.log("this is inside the try block");
return a
}catch{
console.log('error')
}
}
let result = foo();
console.log(result);
答案 0 :(得分:1)
public class TaskFragment extends Fragment {
private static SectionsPagerAdapter sectionsPagerAdapter;
private ArrayList<Task> todo;
private ArrayList<Task> inp;
private ArrayList<Task> done;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_task, container, false);
sectionsPagerAdapter = new SectionsPagerAdapter(getChildFragmentManager());
sectionsPagerAdapter.addFragments(new FragmentToDo(), "To Do");
sectionsPagerAdapter.addFragments(new FragmentInProgress(), "In Progress");
sectionsPagerAdapter.addFragments(new FragmentDone(), "Done");
ViewPager viewPager = view.findViewById(R.id.view_pager);
viewPager.setAdapter(sectionsPagerAdapter);
TabLayout tabs = view.findViewById(R.id.tabs);
tabs.setupWithViewPager(viewPager);
return view;
}
是一个异步函数,它将返回一个Promise。要获得承诺的结果,您将需要链接一个foo
方法:
then
更新:
要使用返回的值,可以在const foo = async()=>{
try{
let a = await new Promise((resolve)=>{
resolve('SUCCESS')
})
console.log("this is inside the try block");
return a
}catch{
console.log('error')
}
}
foo().then(result => console.log(result));
方法内使用它,或使用结果调用另一个函数。
then
OR:
foo().then(result => {
console.log(result);
//do what you want with the result here
});