混合异步操作(回调和保证)完成后如何执行任务?

时间:2016-02-20 13:37:47

标签: node.js asynchronous callback promise

我正在编写一些nodejs应用程序。我的应用程序对某些npm模块有一些依赖。

在任务中,它涉及两个异步操作,两个异步操作是回调和保证的形式。下面我给出了一些示例代码:

public class ResturantListFragment extends Fragment {

    private ArrayList<Resturant> res = new ArrayList<>();
    private ListView resturantList ;
    private ListAdapter adapter;


    public ResturantListFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        final View rootView = inflater.inflate(R.layout.fragment_two, container, false);

        resturantList = (ListView)rootView.findViewById(R.id.listtt);


        String[] names = {"Soho","Rustico","Mac","Yoni","Ofir","Or","mio","north","ao,","fgfg"};
        for (int i=0; i < 10; i++){
            res.add(new Resturant(i,names[i]));
        }
        adapter = new ListAdapter(getContext(),res);
        resturantList.setAdapter(adapter);

        resturantList.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, final View view,
                                    int position, long id) {
                Log.d("press on:","12234234234234");
            }

        });

在上面的例子中,当第一次异步和第二次异步操作完成时,// the task which should be performed after async operation var myTask = function(){ // do something } // first async operation in the form of callback cbapi(myTask) // second async operation in the form of promise promiseapi() .then(myTask) 将执行两次。但我想要的是只有在异步操作完成后才执行一次。

有没有办法做到这一点?

2 个答案:

答案 0 :(得分:2)

正如 @esaukuha 建议的那样,你应该宣传你的回调api,然后再使用它们。

new Promise((resolve, reject) => 
  cbapi((err, result) => {
    if (err) reject(err);
    else resolve(result);
  })
)
  .then(myTask) // ... chain

我只有一个小npm module

import fromCallback from 'promise-cb/from';
fromCallback(cb => cbapi(cb))
  .then(myTask) // ... chain

答案 1 :(得分:0)

围绕回调函数调用构建一个新的Promise,并在两个调用上使用Promise.all

Promise.all([new Promise(resolve => cbapi(resolve)), promiseapi()])
.then(myTask)
.catch(e => console.error(e));
将使用包含两次调用结果的数组调用

myTask