代码之家  ›  专栏  ›  技术社区  ›  Chris

如何让一个函数等待另一个函数使用链接在javascript中完成处理?

  •  1
  • Chris  · 技术社区  · 7 年前

    我有一个函数,它通过firebase的rest api从firebase中提取数组,我需要将这个数组输入到另一个函数中来创建日历。

    function array_from_firebase(){
        //code that pulls from firebase
        return array
    }
    
    function calendar_create_from_array(array){
        //code that generates calendar
    }
    

    以下内容不起作用:

    calendar_create_from_array(array_from_firebase())
    

    但是,这确实有效

    array = array_from_firebase()
    setTimeout(calendar_create_from_array,9000,array)
    

    我相信这意味着从FireBase创建的数组\比从\数组创建日历\和从\数组创建日历\的触发时间要长一些。

    我怎样才能用锁链和承诺来解决这个问题?

    2 回复  |  直到 7 年前
        1
  •  0
  •   brk    7 年前

    setTimeout

    function array_from_firebase() {
      return new Promise(
        function(resolve) {
          setTimeout(function() {
            return resolve([1, 2, 3])
          }, 4000)
        },
        function(reject) {})
    }
    
    function calendar_create_from_array(array) {
      console.log(array);
    }
    
    array_from_firebase().then(function(resp) {
      calendar_create_from_array(resp)
    })

    async await

    function array_from_firebase() {
      return new Promise(
    
        function(resolve) {
          setTimeout(function() {
            return resolve([1, 2, 3])
          }, 5000)
    
        },
        function(reject) {})
    }
    
    async function calendar_create_from_array() {
      console.log('Calling function and waiting for result for 5secs....')
      let getResult = await array_from_firebase();
      console.log('Got result after 5secs', getResult)
    }
    calendar_create_from_array()
        2
  •  0
  •   P.S.    7 年前

    Promise .then .catch array_from_firebase calendar_create_from_array

    function array_from_firebase() {
      // Simulate async response
      return new Promise(function(resolve, reject) {
        setTimeout(function() {
          resolve([1,2,3]);
        }, 3000);
      })
    }
    
    function calendar_create_from_array() {
        array_from_firebase()
          .then(function(response) {
            console.log(response);
          })
    }
    
    calendar_create_from_array();