nodejs7.0 试用 async await

本文地址 http://www.cnblogs.com/jasonxuli/p/6047590.html

nodejs 7.0.0 已经支持使用 --harmony-async-await 选项来开启async 和 await功能。

在我看来,yield 和 async-await 都是在特定范围内实现了阻塞;从这方面来看,await 相当于在阻塞结合异步调用上前进了一步。

使用async前缀定义的function中可以使用await来等待Promise完成(promise.resolve() 或 promise.reject()), 原生Promise或者第三方Promise都可以。

"use strict";

console.log(process.version);

var Promise = require('bluebird');
var requestP = Promise.promisify(require('request'));

async function testAsync(){
    try{
        return await requestP('http://www.baidu.com');
    }catch(e){
        console.log('error', e);
    }
}

var b = testAsync();
b.then(function(r){
    console.log('then');
    console.log(r.body);
});

console.log('done');

node.exe --harmony-async-await test.js

console结果:


v7.0.0
done
then
<!DOCTYPE html><!--STATUS OK-->
<html>
<head>

......

采用await,可以比较容易处理某些Promise必须结合循环的情况,比如:

async getStream(){

    var result = '';

    var chunk = await getChunk();

    while (chunk.done == false){

        result += chunck.data;

        chunk = await getChunk();

    }

}

比较起来,原生Promise看起来样子有些臃肿,而且无法显示错误信息的stack trace;倒是bluebird的promise的stack trace做的不错:

原生:

"use strict";

console.log(process.version);

Promise.resolve('aaa').then(function(){
    throw new Error('error message');
})

console.log('done');

结果:

v7.0.0
(node:7460) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: error message
(node:7460) DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
done

bluebird:

"use strict";

console.log(process.version);

var promise = require('bluebird');

promise.resolve('aaa').then(function(){
    throw new Error('error message');
})

console.log('done');

结果:

v7.0.0
done
Unhandled rejection Error: error message
at f: est est2 est.js:49:11
at tryCatcher (F: odistin ode_modulesluebirdjs eleaseutil.js:16:23)
at Promise._settlePromiseFromHandler (F: odistin ode_modulesluebirdjs eleasepromise.js:510:31)
at Promise._settlePromise (F: odistin ode_modulesluebirdjs eleasepromise.js:567:18)
at Promise._settlePromiseCtx (F: odistin ode_modulesluebirdjs eleasepromise.js:604:10)
at Async._drainQueue (F: odistin ode_modulesluebirdjs eleaseasync.js:143:12)
at Async._drainQueues (F: odistin ode_modulesluebirdjs eleaseasync.js:148:10)
at Immediate.Async.drainQueues (F: odistin ode_modulesluebirdjs eleaseasync.js:17:14)
at runCallback (timers.js:637:20)
at tryOnImmediate (timers.js:610:5)
at processImmediate [as _immediateCallback] (timers.js:582:5)

references:

https://blog.risingstack.com/async-await-node-js-7-nightly/

https://developers.google.com/web/fundamentals/getting-started/primers/async-functions

原文地址:https://www.cnblogs.com/jasonxuli/p/6047590.html