node.js - How to write nodejs callback to await
漂亮男人
漂亮男人 2017-05-17 09:57:09
0
2
717

I have this piece of code


module.exports.AAA=function(){

    let request= test(function(){
        //一段异步代码
    });
    let data;
    
    request.on('data',function(data){})    
    request.on('end',function(){})
}

With the above code, how can I directly obtain the value of data when calling AAA()? How to write if you use async and await?

漂亮男人
漂亮男人

reply all(2)
过去多啦不再A梦
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);
  }
})();
曾经蜡笔没有小新

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
})();

Here is a piece of code for reference.

node --harmony-async-await foobar.js

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template