2-thenable 中文文档教程
2-thenable
Convert object into a thenable
当我们想在一些非承诺对象上暗示异步表示时很有用。
拥有该目标对象可以组合成承诺链或异步/等待语法。 一个用例是转换一个流实例,所以它也是一个承诺。
Installation
npm install 2-thenable
How it works
实用程序采用 target
和 promise
参数。 target
是要使用 then
、catch
和 finally
方法扩展的对象。 虽然 promise
应该是一个原生的 promise 实例,它反映了应该映射到 target
上的分辨率
Usage
。将流转换为可用
const toThenable = require("2-thenable");
// Example of converting a simple utf8 string stream to thenable
toThenable(stream, new Promise((resolve, reject) => {
let result = '';
stream.on('error', reject);
stream.on('data', data => (result += data));
stream.on('end', () => resolve(result));
});
stream.then(result => {
console.log("Cumulated string data", result);
});
Tests
npm test
[npm-image] 的示例:https://img .shields.io/npm/v/2-thenable.svg
2-thenable
Convert object into a thenable
Useful when we want to imply an asynchronous representation onto some non-promise object.
Having that target object can be combined into promise chains or async/await syntax. One use case would be turning a stream instance so it's also a promise.
Installation
npm install 2-thenable
How it works
Utility takes target
and promise
arguments. target
is object to be extended with then
, catch
and finally
methods. While promise
is expected to be a native promise instance that reflects resolution which should be mapped onto target
Usage
Example of converting stream to thenable
const toThenable = require("2-thenable");
// Example of converting a simple utf8 string stream to thenable
toThenable(stream, new Promise((resolve, reject) => {
let result = '';
stream.on('error', reject);
stream.on('data', data => (result += data));
stream.on('end', () => resolve(result));
});
stream.then(result => {
console.log("Cumulated string data", result);
});
Tests
npm test
[npm-image]: https://img.shields.io/npm/v/2-thenable.svg