2016-09-26 64 views
0

在switch語句中是否可以有生成器? 由於在函數中可能不總是回傳一個生成器?「可選」生成器在switch語句中?

在代碼:

function* getWebsite ($) { 
    const contents = $('.selector-blah'); 
    if (contents) { 
    const resp = yield http.getHTML({ url: contents.href }); 
    return resp.finalUrl; 
    } else { 
    return null; 
    } 
} 

const selectorMappings = { 
    name: '#name', 
    starRating: getStarRating, // normal function 
    website: getWebsite // generator function 
} 

yield processSelectors($, data, selectorMappings); 
// <code> here is excuting before yield is complete above. 

processSelectors模塊:

const _ = require('lodash'); 
const sanitizeText = require('./sanitizeText'); 

module.exports = function* processSelectors ($, data, selectors = {}, route = '') { 
    const keys = Object.keys(selectors); 
    for (let key of keys) { 
    let path = route ? route + '.' + key : key; 
    switch (selectors[key].constructor.name) { 
     case 'String': 
     _.set(data, path, sanitizeText($(selectors[key]).first().text())); 
     break; 
     case 'Function': 
     _.set(data, path, selectors[key]($)); 
     break; 
     case 'GeneratorFunction': 
     var result = yield selectors[key]($); 
     _.set(data, path, result); 
     break; 
     case 'Object': 
     _.set(data, path, {}); 
     processSelectors($, data, selectors[key], path); 
     break; 
    } 
    } 
}; 

我確實有一個foreach裏面的開關,但搬出來避免嵌套功能,但並沒有幫助,也採用共嘗試和與Promise一起合作。

+2

一個函數或者是發電機或者它不是。它不應該(不能)在運行時決定它想做什麼。 *主叫方將如何知道它決定的是什麼? – deceze

+0

你可以編寫一個永遠不會產生的生成器函數,但是你不應該寫一個只有時返回一個生成器的函數。 – Bergi

+0

那裏'yield processSelectors($,data,selectorMappings);'調用? – Bergi

回答

0

通過使整個事情發電機得到這個工作:

yield processSelectors($, data, selectorMappings); 

//////////////////////////////////////////////////////// 
//      MODULE      // 
//////////////////////////////////////////////////////// 

const _ = require('lodash'); 
const sanitizeText = require('./sanitizeText'); 

module.exports = function* processSelectors ($, data, selectors = {}, route = '') { 
    const keys = Object.keys(selectors); 
    for (let key of keys) { 
    let path = route ? route + '.' + key : key; 
    switch (selectors[key].constructor.name) { 
     case 'String': 
     _.set(data, path, sanitizeText($(selectors[key]).first().text())); 
     break; 
     case 'Function': 
     _.set(data, path, selectors[key]($)); 
     break; 
     case 'GeneratorFunction': 
     _.set(data, path, yield selectors[key]($)); 
     break; 
     case 'Object': 
     _.set(data, path, {}); 
     processSelectors($, data, selectors[key], path); 
     break; 
    } 
    } 
};