本文整理汇总了TypeScript中ts-promise.Promise.defer方法的典型用法代码示例。如果您正苦于以下问题:TypeScript Promise.defer方法的具体用法?TypeScript Promise.defer怎么用?TypeScript Promise.defer使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ts-promise.Promise
的用法示例。
在下文中一共展示了Promise.defer方法的2个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的TypeScript代码示例。
示例1:
(chunk: any): void|Promise<void> => {
// Try to push data, returns true if there's still space
if (this.push(chunk)) {
return;
}
// Stream blocked, wait until _read() is called
let d = Promise.defer();
this._resumer = d.resolve;
return d.promise;
},
示例2: handleNodeStreamError
export function pipeToNodeStream<T>(
tsReadable: Readable<T>,
nodeWritable: NodeJS.WritableStream,
emitError: boolean = false
): Promise<void> {
let endDeferred = Promise.defer();
let blockedDeferred: VoidDeferred;
// Handle errors emitted by node stream: abort ts-stream
function handleNodeStreamError(error: Error): void {
// Don't 're-emit' the same error on which we were triggered
emitError = false;
// Make sure stream's end result reflects error
endDeferred.reject(error);
tsReadable.abort(error);
if (blockedDeferred) {
blockedDeferred.reject(error);
nodeWritable.removeListener("drain", blockedDeferred.resolve);
}
}
// Optionally pass ts-stream errors to node stream
function handleTsStreamError(error: Error): void {
if (!emitError) {
return;
}
emitError = false;
nodeWritable.removeListener("error", handleNodeStreamError); // prevent abort
nodeWritable.emit("error", error);
}
nodeWritable.once("error", handleNodeStreamError);
nodeWritable.once("finish", () => {
nodeWritable.removeListener("error", handleNodeStreamError);
endDeferred.resolve(); // ignored if error happens earlier
});
return tsReadable.forEach(
(chunk: any): void|Promise<void> => {
blockedDeferred = undefined;
// Try to push data, returns true if there's still space
let canAcceptMore = nodeWritable.write(chunk);
if (!canAcceptMore) {
// Stream blocked, wait until drain is emitted
blockedDeferred = Promise.defer();
nodeWritable.once("drain", blockedDeferred.resolve);
return blockedDeferred.promise;
}
},
(endError?: Error): Promise<void> => {
if (endError) {
handleTsStreamError(endError);
}
// Note: we don't pass a callback to end(), as some types of
// streams (e.g. sockets) may forget to call the callback in
// some scenarios (e.g. connection reset).
// We use the "finish" event to mark the stream's end, but it
// doesn't get emitted on e.g. a connection refused error.
nodeWritable.end();
return endDeferred.promise;
},
handleTsStreamError // abort handler
);
}