2017-02-12 32 views
1

我試圖做一些事情,如果該值不存在,所以我可以更新它。但isExist函數總是返回undefined。我能用這個做什麼?返回true實際返回undefined使用async

參考:Ero已被定義。

async.forEachOf(idArray, function(value, key, cb) { 
    rp(baseURL + value) 
     .then(function(json) { 
      if (!isExist(json)) { 
       // do something 
      } else { 
       console.log(isExist(json), "It's not video or exists"); 
      } 
     }) 
    .catch(function(err) { 
     console.error(err); 
    }) 
    cb(); 
    }, function() { 
    res.status(200) 
    }); 
}); 

function isExist(data) { 
    let parsedData = JSON.parse(data); 
    if (parsedData.items[0].type === 'Video') { 
    Ero.find({ 
     videoUri: parsedData.items[0].url_mp4 
    }, function(err, docs) { 
     if (docs.length) { 
      return true; 
     } else { 
      return false; 
     } 
    }) 
    } else { 
     return false; 
    } 
} 
+0

一個的jsfiddle將是很好 – Mazz

回答

0

讓我們看看你的isExist函數。

function isExist(data) { 
    let parsedData = JSON.parse(data); 
    if (parsedData.items[0].type === 'Video') { 
    Ero.find({ 
     videoUri: parsedData.items[0].url_mp4 
    }, function(err, docs) { 
     if (docs.length) { 
      return true; 
     } else { 
      return false; 
     } 
    }) 
    } else { 
     return false; 
    } 
} 

在該函數中,您有兩個分支在條件。當條件爲false時,else塊將運行 - 返回false。當條件爲true時,第一個塊將運行,但是沒有返回語句,因此隱式返回undefined

你說「爲什麼它沒有返回聲明?」我很確定我有一個

看起來像你有一個在這裏。

if (docs.length) { 
    return true; 
} else { 
    return false; 
} 

但是看看它返回哪個函數。它只返回回傳給Ero.find的回調函數,它不返回isExist

你問「我能做些什麼呢?」

我假設Ero.find是一個異步函數,因此isExist也將成爲一個異步函數。要在JavaScript中執行異步功能,您可以使用Promisesasync functions

下面是一些isExist可能與Promise相似的示例代碼。

function isExist(data) { 
    /** 
    * `isExist` returns a Promise. This means the function _promises_ to have a value resolved in the future. 
    */ 
    return new Promise((resolve, reject) => { 
    let parsedData = JSON.parse(data); 
    if (parsedData.items[0].type === 'Video') { 
     Ero.find({ 
     videoUri: parsedData.items[0].url_mp4 
     }, function(err, docs) { 
     if (docs.length) { 
      /** 
      * Once `Ero.find` has completed, `resolve` `isExist` with a value of `true`, otherwise `resolve` `isExist` with a value of `false`. 
      */ 
      resolve(true); 
     } else { 
      resolve(false); 
     } 
     }) 
    } else { 
     /** 
     * You can resolve a Promise even without performing an asynchronous operation. 
     */ 
     resolve(false); 
    } 
    }); 
} 

進一步閱讀

0

如果JSON有語法錯誤,那麼使用JSON.parse會使您有發生異常的風險。使用try/catch塊。

不知道你的數據我不能說你的支票還有什麼問題。

function isExists(data){ 
    try{ 
    var parsedData = JSON.parse(data); 
    if (parsedData.items[0].type === 'Video') { 
     Ero.find({ 
     videoUri: parsedData.items[0].url_mp4 
     }, function(err, docs) { 
     if (docs.length) { 
      return true; 
     } else { 
      return false; 
     } 
     }) 
    } else { 
     return false; 
    } 
    }catch(e) { 
    // any error 
    return false; 
    } 
} 
+0

它沒有得到我的任何錯誤 – boombamboo

+0

然後上傳您的數據。 –