Dive into secure and efficient coding practices with our curated list of the top 10 examples showcasing 'co' in functional components in JavaScript. Our advanced machine learning engine meticulously scans each line of code, cross-referencing millions of open source libraries to ensure your implementation is not just functional, but also robust and secure. Elevate your React applications to new heights by mastering the art of handling side effects, API calls, and asynchronous operations with confidence and precision.
describe("includeExistingRepo", function () {
after(TestUtil.cleanup);
// for these tests, "externalRepo" represents the repository to be
// included and "submoduleRepo" represents the submodule once it
// has been included inside "repo"
let repo, externalRepo, path;
before(co.wrap(function *() {
repo = yield TestUtil.createSimpleRepository();
externalRepo = yield TestUtil.createSimpleRepository();
path = "foo";
yield Include.include(repo, externalRepo.workdir(), path);
}));
it("should include in the correct path", co.wrap(function *() {
const pathExists =
yield TestUtil.pathExists(repo.workdir() + path);
assert(pathExists, "path should exist");
const submoduleRepo =
yield NodeGit.Repository.open(repo.workdir() + path);
assert(submoduleRepo.workdir(), "repository should be created");
}));
function fetchArchiveInfo() {
return co(function* () {
console.log('Looking up', siteKey)
// run request
siteInfo = yield datInternalAPI.getArchiveInfo(siteKey)
siteEntriesTree = entriesListToTree(siteInfo)
siteName = (siteInfo.name || siteInfo.short_name || 'Untitled')
document.title = siteName + ' - Site Editor'
console.log(siteName, siteInfo)
}).catch(err => {
console.warn('Failed to fetch archive info', err)
siteError = err
})
}
BoLogger.prototype.log = function (data) {
co.call(this, function* () {
//data.essence = yield * common.getEssenceId(data.object);
if (data.object) {
yield this.init(data.object, data.req);
}
if (typeof data.entities === 'object') {
data.entities = JSON.stringify(data.entities);
}
var thunkQuery = (data.req) ? data.req.thunkQuery : thunkify(new Query(config.pgConnect.adminSchema));
if (data.user) {
data.userid = (data.user.roleID === 1) ? 0 - data.user.id : data.user.id; // if superuser - then user = -id
}
this.extend(data);
var id = yield thunkQuery(Log.insert(this.data).returning(Log.id));
return data;
}).then(function (data) {
ready() {
log.silly('Message', 'ready()')
return co.call(this, function* () {
const from = Contact.load(this.obj.from)
const to = Contact.load(this.obj.to)
const room = this.obj.room ? Room.load(this.obj.room) : null
if (from) { yield from.ready() } // Contact from
if (to) { yield to.ready() } // Contact to
if (room) { yield room.ready() } // Room member list
return this // return this for chain
}).catch(e => { // Exception
log.error('Message', 'ready() exception: %s', e)
console.log(e)
throw e
})
}
initBrowser() {
log.verbose('PuppetWeb', 'initBrowser()')
const browser = new Browser({
head: this.head
, sessionFile: this.profile
})
browser.on('dead', Event.onBrowserDead.bind(this))
// fastUrl is used to open in browser for we can set cookies.
// backup: 'https://res.wx.qq.com/zh_CN/htmledition/v2/images/icon/ico_loading28a2f7.gif'
const fastUrl = 'https://wx.qq.com/zh_CN/htmledition/v2/images/webwxgeticon.jpg'
return co.call(this, function* () {
yield browser.init()
yield browser.open(fastUrl)
yield browser.loadSession()
.catch(e => { // fail safe
log.verbose('PuppetWeb', 'browser.loadSession(%s) exception: %s', this.profile, e.message || e)
})
yield browser.open()
return browser // follow func name meaning
}).catch(e => {
log.error('PuppetWeb', 'initBrowser() exception: %s', e.message)
throw e
})
}
'content': messageContent,
});
return this.emitPacket(tunnelIds, packetType, packetContent);
},
emitPacket(tunnelIds, packetType, packetContent) {
let param = { tunnelIds, 'type': packetType };
if (packetContent) {
param.content = packetContent;
}
return this._sendRequest('/ws/push', [param], false);
},
_sendRequest: co.wrap(function *(apiPath, apiParam, withTcKey) {
let url = config.getTunnelServerUrl() + apiPath;
let data = this._packReqData(apiParam, withTcKey);
let params = { url, 'body': data };
let begin = Date.now();
let result = yield net.jsonPost(params);
let end = Date.now();
let statusCode = result[0].statusCode;
let body = result[1];
// 记录请求日志
debug(`POST ${url} => [${statusCode}]`, {
'[请求]': data,
'[响应]': body,
/**
* Return a list the files in the specified `repo` and its *open* submodules,
* relative to the root of the repository, or to the optionally specified
* `relativePath` if provided. Note that the order of the list is
* not defined. Note that if `relativePath` is provided, no files will be
* listed that are not within that subdirectory. The behavior is undefined
* unless `relativePath` (if provided) is a valid relative path and has no
* trailing slash.
*
* @async
* @param {NodeGit.Repository} repo
* @param {String} [relativePath]
* @return [String]
*/
exports.listFiles = co.wrap(function *(repo, relativePath) {
assert.instanceOf(repo, NodeGit.Repository);
if (undefined !== relativePath && null !== relativePath) {
assert.isString(relativePath);
assert.notEqual(relativePath, "");
assert.notEqual(relativePath[relativePath.length - 1], "/");
assert(!path.isAbsolute(relativePath));
}
const subNames = new Set(yield SubmoduleUtil.getSubmoduleNames(repo));
const openSubs = yield SubmoduleUtil.listOpenSubmodules(repo);
const result = [];
let withSlash; // the relative path with a suffixed '/'
if (relativePath) {
withSlash = relativePath + "/";
}
WorkerQueue.prototype.fork = function () {
cluster.setupMaster({ args: [ 'worker-queue' ] });
let worker = cluster.fork(),
log = this.__pool.log;
worker.on('online', co.wrap(function* () {
try {
// Set scheduling policy to SCHED_IDLE (`-i` flag);
// `0` is only possible value for priority ('cause this policy doesn't allow to set it)
yield execFile('chrt', [ '-i', '-p', '0', worker.process.pid ]);
} catch (__) {
// If `chrt` not exists, try fallback to `renice`.
try {
yield execFile('renice', [ '-n', '19', '-p', worker.process.pid ]);
log.warn('Cannot set scheduling policy for queue using `chrt`, falling back to `renice`');
} catch (___) {
log.error('Cannot lower priority for queue ' +
'(both `renice` and `chrt` have failed), continuing with default priority');
}
}
}));
send(request, url, options={}) {
return co(function *() {
let sandbox = options.sandbox;
let transformRequest = request.transformRequest;
let transformResponse = request.transformResponse;
let onerror = request.onerror;
if (!('retry' in options)) options.retry = true;
let result, xhr;
try {
let token = yield access(this.credentials, options);
xhr = new XMLHttpRequest();
if (sandbox) sandbox.add(xhr);
xhr.open(request.method, url, true /* async */);
xhr.setRequestHeader('Authorization', `Bearer ${token}`);
if (transformRequest) transformRequest(xhr);
xhr.setRequestHeader('requesttoken', oc_requesttoken);
return new Promise((resolve, reject) => {
co(function*() {
// Only connect if not already connected
if(!self.backend.isConnected()) {
yield self.backend.connect(url)
}
// Resolve
resolve(self);
}).catch(reject);
});
}