当前位置: 首页>>代码示例>>TypeScript>>正文


TypeScript bluebird.promisify函数代码示例

本文整理汇总了TypeScript中bluebird.promisify函数的典型用法代码示例。如果您正苦于以下问题:TypeScript promisify函数的具体用法?TypeScript promisify怎么用?TypeScript promisify使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了promisify函数的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的TypeScript代码示例。

示例1: load

export async function load () {
  const readFileAsync = Bluebird.promisify(fs.readFile);
  const readdirAsync = Bluebird.promisify(fs.readdir);

  const files = await readdirAsync(roomsPath).map(f => path.join(roomsPath, f as any));

  // Load rooms from files, using the filename as the ID.
  const roomArr = await Bluebird.map(files, async function (f) {
    const roomData = await readFileAsync(f as any).then(data => yaml.safeLoad(data.toString()));
    roomData.roomID = path.parse(f).name;
    return roomData;
  });

  roomArr.forEach(r => rooms.set(r.roomID, new Room(r)));
}
开发者ID:euoia,项目名称:node-mud,代码行数:15,代码来源:world.ts

示例2: access

const serverWithPromise = http.createServer((req: http.IncomingMessage, res: http.ServerResponse) => {
    // Local variables
    let lookup = path.basename(decodeURI(req.url)) || 'index.html';
    let filePath = `./content/${lookup}`

    let access = Promise.promisify(fs.access);
    access(filePath)
        .then(cacheHandle)
        .then(responseHandle)
        .catch(errorHandle);

    //////// hoisted functions

    function cacheHandle() {
        let cachePromise = Promise.promisify(cacheAndDeliver);
        return cachePromise(filePath);
    }

    function responseHandle(data: Buffer) {
        let headers = { 'Content-type': mimeTypes[path.extname(lookup)] };
        res.writeHead(200, headers);
        res.end(data);
    }

    function errorHandle(err) {
        res.writeHead(500);
        res.end('ServerError!');
        return;
    }

}).listen(8081, () => {
开发者ID:TonyPythoneer,项目名称:node-cookbook,代码行数:31,代码来源:app.ts

示例3: newNormalize

	function newNormalize(
		name: string,
		parentName: string,
		parentAddress: string,
		pathName: string
	) {
		const indexName = pathName.replace(/.js$/, '/index.js');

		if(builder.loader.map) {
			const other = builder.loader.map[name];
			if(other && other != name) {
				return(builder.loader.normalize(other, parentName, parentAddress));
			}
		}

		return(
			Promise.promisify(fs.stat)(
				url2path(indexName)
			).then((stats: fs.Stats) => {
				const oldPath = url2path(pathName);
				const newPath = url2path(indexName);

				// TODO: test on Windows
				fixTbl[oldPath] = newPath;

				return(indexName);
			}).catch((err: NodeJS.ErrnoException) =>
				findPackage(name, parentName, basePath, fixTbl, repoTbl)
			).catch((err: any) =>
				pathName
			)
		);
	}
开发者ID:charto,项目名称:cbuild,代码行数:33,代码来源:cbuild.ts

示例4: cacheAndDeliverWithPromise

function cacheAndDeliverWithPromise(f: string,
                                    cb: (err: NodeJS.ErrnoException, data: Buffer) => void) {
    // Wrap fs.stat in Promise
    let stat = Promise.promisify(fs.stat);
    stat(f).then((stats: fs.Stats) => {
        let lastChanged: number = Date.parse(stats.ctime.toString())
        let isUpdated: boolean = (cache[f]) && lastChanged > cache[f].timestamp;

        // Check the file is existent/updated or not
        if (!cache[f] || isUpdated) {
            // Wrap fs.readFile in Promise
            let readFile = Promise.promisify(fs.readFile);
            readFile(f).then((data) => {
                console.log('loading ' + f + ' from file');
                cache[f] = { content: data, timestamp: Date.now() };
                cb(null, data);
            }).catch((err) => {
                cb(err, null);
            })
            return;
        }

        // Loading from cache
        console.log(`loading ${f} from cache`);
        cb(null, cache[f].content);
    }).catch((err) => {
        return console.log('Oh no!, Eror', err);
    });
}
开发者ID:TonyPythoneer,项目名称:node-cookbook,代码行数:29,代码来源:app.ts

示例5:

	const dependenciesDone = Promise.map(config.dependencies || [], (dep: string) =>
		// Find package.json file of required module.

		Promise.promisify(resolve)(
			dep,
			{
				basedir: basePath,
				packageFilter: (json: any) => {
					json.main = 'package.json';
					return(json);
				}
			}
		).then((entry: string) =>
			// Parse possible autogypi.json file specifying how to include the module.

			parseConfig(
				path.resolve(path.dirname(entry), 'autogypi.json')
			).catch((err: any) => {
				// No configuration file found, just add the root directory to include paths.
				// This is enough for nan.

				const pair: GypiPair = {
					gypi: {
						'include_dirs': [ path.dirname(entry) ]
					}
				};

				return(pair);
			})
		)
开发者ID:charto,项目名称:autogypi,代码行数:30,代码来源:autogypi.ts

示例6: cropTo

 /**
  *  Crops image and saves it to outImage
  */
 public cropTo(outImage: string, done: DoneCallback) {
   if (done) {
     return this._cropTo(outImage, done);
   }
   const cropTo = Promise.promisify(this._cropTo, {context: this});
   return cropTo(outImage);
 }
开发者ID:apedyashev,项目名称:opticrop-node,代码行数:10,代码来源:opticrop.ts

示例7: getMigrations

  /**
   * Get all migrations from the directory.
   *
   * @returns {Bluebird<string[]>}
   */
  public getMigrations(): Promise<Array<string>> {
    return Promise.promisify(fs.readdir)(this.config.directory).then(contents => {
      const regexp = new RegExp(`\.${this.config.extension}$`);

      return contents
        .filter(migration => migration.search(regexp) > -1)
        .map(migration => migration.replace(regexp, ''))
        .sort();
    });
  }
开发者ID:RWOverdijk,项目名称:wetland,代码行数:15,代码来源:MigrationFile.ts

示例8: getTypingsFileForModuleName

    private getTypingsFileForModuleName(baseDir: string, moduleName: string): Promise<string> {
        let nodeModulesFolder = path.join(baseDir, "node_modules");
        let moduleFolder = path.join(nodeModulesFolder, moduleName);
        let modulePackage = path.join(moduleFolder, "package.json");

        return Promise.promisify(fs.readFile)(modulePackage).then(data => {
            let typingsFile = JSON.parse(data.toString()).typings || "index.d.ts";
            return path.join(moduleFolder, typingsFile);
        });
    }
开发者ID:AndyMoreland,项目名称:tsunami-emacs,代码行数:10,代码来源:tsProject.ts

示例9: it

 it('will return error when user is not in mongo', function (done) {
     var id = monk.id();
     var expectedUser = {_id: id, uniqueValue: 'bloopers'};
     Promise.promisify(userDataService.deserializeUser)(expectedUser._id)
         .then(function () {
             fail('This should have thrown an error.');
         }, function (error) {
             expect(error.message).toEqual('The user with id: ' +
                 id + ' could not be found in the database.');
         })
         .then(done, done.fail);
 });
开发者ID:robertfmurdock,项目名称:Coupling,代码行数:12,代码来源:UserDataService-spec.ts

示例10: loadBMS

 async loadBMS(
   arraybuffer: Buffer | ArrayBuffer,
   resource: NotechartLoaderResource,
   options: PlayerOptions
 ) {
   let buffer = coerceToBuffer(arraybuffer)
   let readerOptions = BMS.Reader.getReaderOptionsFromFilename(resource.name)
   let source = await Bluebird.promisify<string, Buffer, BMS.ReaderOptions>(
     BMS.Reader.readAsync
   )(buffer, readerOptions)
   let compileResult = BMS.Compiler.compile(source)
   let chart = compileResult.chart
   let notechart = BMSNotechartLoader.fromBMSChart(chart, options)
   return notechart
 }
开发者ID:bemusic,项目名称:bemuse,代码行数:15,代码来源:index.ts


注:本文中的bluebird.promisify函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。