我试图通过屈服于允许其他服务器请求查看的事件循环来使 React 成为更好的公民,renderToString
例如renderToStaticMarkup
const React = require('react');
const { renderToNodeStream } = require('react-dom/server');
// Wrap `renderToNodeStream` in promise
const renderToStringAsync = node => {
return new Promise((resolve, reject) => {
let body = '';
const stream = renderToNodeStream(node);
// NOTE: we're turning the tap on full blast here, but I still expected it to yield
stream.on('data', chunk => {
console.log('Received chunk');
body += chunk.toString();
});
stream.on('error', ex => {
reject(ex);
});
stream.on('end', () => {
resolve(body);
});
});
};
setTimeout(() => {
console.log('Yielded to event loop');
}, 0)
await renderToStringAsync(largeRootNode);
我期待这个:
// Expect:
// Received chunk
// Yielded to event loop
// Received chunk
// Received chunk
// Received chunk
// Received chunk
// Received chunk
// Received chunk
// Received chunk
// Received chunk
// Received chunk
但我实际上得到了这个:
// Actual:
// Received chunk
// Received chunk
// Received chunk
// Received chunk
// Received chunk
// Received chunk
// Received chunk
// Received chunk
// Received chunk
// Yielded to event loop
我想知道它是否与.on('data')
; 我知道它不能管理背压,但我一直认为它是异步的?
注意:我没有将响应传递给客户端,因为我需要等待渲染完成才能确定状态代码;我只是想用来
renderToNodeStream
改进 node.js 中的协作多任务处理)