Rumah > Soal Jawab > teks badan
Saya ada sekeping kod seperti ini
module.exports.AAA=function(){
let request= test(function(){
//一段异步代码
});
let data;
request.on('data',function(data){})
request.on('end',function(){})
}
Bagaimana cara saya memanggil kod di atas AAA()
的时候直接获取到data
的值呢?如果是使用async
和await
Bagaimana cara saya menulisnya?
过去多啦不再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
})();
Berikut adalah sekeping kod untuk rujukan.
nod --harmony-async-wait foobar.js