Home > database >  Get and return value outside function - Nodejs
Get and return value outside function - Nodejs

Time:12-04

I'm working on some method that have a callback with value, that I need to return and response, but value is null outside callback funciton How can I solve?

async function createChannel(req) {
  let user_id = req.query.user_id;
  let chat_name = req.query.chat_name;
  var chimesdkmessaging = new AWS.ChimeSDKMessaging({region: region});

  var channel = null;

  try {
    let dateNow = new Date();
    const params = {
      Name: chat_name,
      AppInstanceArn: config.aws_chime_app_istance,
      ClientRequestToken: dateNow.getHours().toString()   dateNow.getMinutes().toString(),
      ChimeBearer: await AppInstanceUserArn(user_id),
      AppInstanceUserArn of the user making the API call.
      Mode: 'RESTRICTED',
      Privacy: 'PRIVATE'
    };

    chimesdkmessaging.createChannel(params, function (err, data) {
      if (err) {
        console.log(err, err.stack);
      } // an error occurred
      else {
        console.log(data);           // successful response
        console.log('Assegno il canale: '   data.ChannelArn);
        channel = data.ChannelArn; // <----- VALUE I WANT TO RETURN OUTSIDE
      }
    });
  } catch (e) {
    return response({error: e}, 500);
  }
  return response({data: channel},200); // <---- but this channel is null
}

CodePudding user response:

wrap with Promise

  let user_id = req.query.user_id;
  let chat_name = req.query.chat_name;
  var chimesdkmessaging = new AWS.ChimeSDKMessaging({region: region});

  let channel = null;

  try {
    let dateNow = new Date();
    const params = {
      Name: chat_name,
      AppInstanceArn: config.aws_chime_app_istance,
      ClientRequestToken: dateNow.getHours().toString()   dateNow.getMinutes().toString(),
      ChimeBearer: await AppInstanceUserArn(user_id),
      AppInstanceUserArn of the user making the API call.
      Mode: 'RESTRICTED',
      Privacy: 'PRIVATE'
    };

    channel = await new Promise((resolve,reject)=>{
    chimesdkmessaging.createChannel(params, function (err, data) {
      if (err) {
        console.log(err, err.stack);
        reject(err)
      } // an error occurred
      else {
        console.log(data);           // successful response
        console.log('Assegno il canale: '   data.ChannelArn);
        resolve(data.ChannelArn)// <----- VALUE I WANT TO RETURN OUTSIDE
      }
    });
    })

  } catch (e) {
    return response({error: e}, 500);
  }
  return response({data: channel},200); // <---- but this channel is null
}
  • Related