是否可以在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中有一个开关但移出来避免嵌套函数但没有帮助,也尝试使用co和co.wrap,以及Promise的。
答案 0 :(得分: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;
}
}
};