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:\test\test2\test.js:49:11
at tryCatcher (F:\nodist\bin\node_modules\bluebird\js\release\util.js:16:23)
at Promise._settlePromiseFromHandler (F:\nodist\bin\node_modules\bluebird\js\release\promise.js:510:31)
at Promise._settlePromise (F:\nodist\bin\node_modules\bluebird\js\release\promise.js:567:18)
at Promise._settlePromiseCtx (F:\nodist\bin\node_modules\bluebird\js\release\promise.js:604:10)
at Async._drainQueue (F:\nodist\bin\node_modules\bluebird\js\release\async.js:143:12)
at Async._drainQueues (F:\nodist\bin\node_modules\bluebird\js\release\async.js:148:10)
at Immediate.Async.drainQueues (F:\nodist\bin\node_modules\bluebird\js\release\async.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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM