Heim > Fragen und Antworten > Hauptteil
Ich habe einen Code wie diesen
module.exports.AAA=function(){
let request= test(function(){
//一段异步代码
});
let data;
request.on('data',function(data){})
request.on('end',function(){})
}
Wie rufe ich den obigen Code auf? AAA()
的时候直接获取到data
的值呢?如果是使用async
和await
Wie schreibe ich ihn?
过去多啦不再A梦2017-05-17 09:59:09
npm install bluebird --save
const Promise = require('bluebird');
module.exports.AAA=function(){
return new Promise((resolve,reject)=>{
let request= test(function(){
//一段异步代码
});
request.on('data',resolve);
request.on('error',reject);
request.on('end',function(){});
});
}
(async function(){
try{
const response = await AAA();
console.log(response);
}catch(e){
console.error(e);
}
})();
曾经蜡笔没有小新2017-05-17 09:59:09
foobar.js
'use strict';
function getDelayedData() {
return new Promise(async resolve => {
setTimeout(() => { resolve(+new Date); }, 1000);
});
}
(async () => {
let result = await getDelayedData();
console.log('Got', result); // missing error checking
})();
这里有一段代码参考一下。
node --harmony-async-await foobar.js