Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/463.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 将值从异步函数返回到外部函数节点js_Javascript_Jquery_Node.js_Asynchronous_Twilio - Fatal编程技术网

Javascript 将值从异步函数返回到外部函数节点js

Javascript 将值从异步函数返回到外部函数节点js,javascript,jquery,node.js,asynchronous,twilio,Javascript,Jquery,Node.js,Asynchronous,Twilio,我对这个世界还很陌生。必须开始通过节点实现Twilio视频呼叫 我一直在尝试调用这个服务器端函数,然后调用另一个返回promise的异步函数。then部分工作正常,我能够在控制台中看到输出。但当我尝试在中调用另一个函数时,它对主应用程序进行了ajax调用,以在数据库中保存一些数据 我既不能在response.send()中发送返回值,也不能在response.send()中调用函数 请帮忙 服务器端-index.js 'use strict'; /** * Load Twilio confi

我对这个世界还很陌生。必须开始通过节点实现Twilio视频呼叫

我一直在尝试调用这个服务器端函数,然后调用另一个返回promise的异步函数。then部分工作正常,我能够在控制台中看到输出。但当我尝试在中调用另一个函数时,它对主应用程序进行了ajax调用,以在数据库中保存一些数据

我既不能在response.send()中发送返回值,也不能在response.send()中调用函数

请帮忙

服务器端-index.js

'use strict';

/**
 * Load Twilio configuration from .env config file - the following environment
 * variables should be set:
 * process.env.TWILIO_ACCOUNT_SID
 * process.env.TWILIO_API_KEY
 * process.env.TWILIO_API_SECRET
 */
require('dotenv').load();

const express = require('express');
const http = require('http');
const path = require('path');
const { jwt: { AccessToken } } = require('twilio');
const Twilio = require('twilio');
const jquery = require( 'jQuery');
const cors = require('cors');

const VideoGrant = AccessToken.VideoGrant;

// Max. period that a Participant is allowed to be in a Room (currently 14400 seconds or 4 hours)
const MAX_ALLOWED_SESSION_DURATION = 14400;

// Create Express webapp.
const app = express();

// Set up the path for the HealthAssure.
const startPath = path.join(__dirname, '../HAVideoConsultation/public');
app.use('/HAVideoConsultation', express.static(startPath));

/**
 * Default to the application.
 */
app.get('/', (request, response) => {
  response.redirect('/HAVideoConsultation');
});

/**
 * Generate an Access Token for a chat application user - it generates a random
 * username for the client requesting a token, and takes a device ID as a query
 * parameter.
 */
app.get('/token', function(request, response) {
  const { identity } = request.query;

  // Create an access token which we will sign and return to the client,
  // containing the grant we just created.
  const token = new AccessToken(
    process.env.TWILIO_ACCOUNT_SID,
    process.env.TWILIO_API_KEY,
    process.env.TWILIO_API_SECRET,
    { ttl: MAX_ALLOWED_SESSION_DURATION }
  );

  // Assign the generated identity to the token.
  token.identity = identity;

  // Grant the access token Twilio Video capabilities.
  const grant = new VideoGrant();
  token.addGrant(grant);

  // Serialize the token to a JWT string.
  response.send(token.toJwt());
});

function pushCompositionId(compositionId){
    console.log(compositionId);
    jquery.ajax({            
        url:'http://localhost:58674/ABC/XYZ',
        type:'GET',
        data: {CompositionId:compositionId},
        cors: true,
        success:function(result){ 
            Console.log('Composition Id pushed successfully.');
        },
        error:function(err){
            console.log(err);
            return false;
        }            
    });
} 


app.get('/Composition',function(request,response){
    const client = new Twilio(process.env.TWILIO_API_KEY,process.env.TWILIO_API_SECRET, {accountSid: process.env.TWILIO_ACCOUNT_SID}); 
    const cid = null;
    client.video.compositions
        .create({
        roomSid: request.query.roomSid,
        audioSources: '*',
        videoLayout: {
          grid : {  
            video_sources: ['*']
          }
        },     
        format: 'mp4'
      }).then(composition =>{      
    console.log("Created Composition with SID=" + composition.sid); // This works properly
    cid=composition.sid;
    // pushCompositionId(composition.sid); // I want to call this function here
  });
  response.send(cid); // This does not return proper value
});

// Create http server and run it.
const server = http.createServer(app);
const port = process.env.PORT || 3000;
server.listen(port, function() {
  console.log('Express server running on *:' + port);
});

客户端

async function GenerateCompositionId(roomsid){
const compositionid = await fetch(`/Composition?roomSid=${roomsid}`);  
}
生成Composition.sid后,我要调用的服务器端函数。如果我把它放在一个try块中,它会给我错误jquery.ajax不是一个函数。我已经包含了它,并且客户端的另一个ajax功能运行良好。为什么不呢

function pushCompositionId(compositionId){
    jquery.ajax({            
        url:'http://localhost:58674/ABC/XYZ',
        type:'GET',
        data: {CompositionId:compositionId},
        cors: true,
        success:function(result){ 
            Console.log('Composition Id pushed successfully.');
        },
        error:function(err){
            console.log(err);
            return false;
        }            
    });
} 

为了在异步调用完成时发送响应,服务器端必须:

var jsdom = require("jsdom");
const { JSDOM } = jsdom;
const { window } = new JSDOM();
const { document } = (new JSDOM('')).window;
global.document = document;

var $ = jQuery = require('jquery')(window);

function pushCompositionId(compositionId,response){
    console.log(compositionId);
    jquery.ajax({            
        url:'http://localhost:58674/ABC/XYZ',
        type:'GET',
        data: {CompositionId:compositionId},
        cors: true,
        success:function(result){ 
            Console.log('Composition Id pushed successfully.');
            response.send(cid); // This does not return proper value
        },
        error:function(err){
            console.log(err);
            response.send(false);
        }            
    });
} 


app.get('/Composition',function(request,response){
    const client = new Twilio(process.env.TWILIO_API_KEY,process.env.TWILIO_API_SECRET, {accountSid: process.env.TWILIO_ACCOUNT_SID}); 
    const cid = null;
    client.video.compositions
        .create({
        roomSid: request.query.roomSid,
        audioSources: '*',
        videoLayout: {
          grid : {  
            video_sources: ['*']
          }
        },     
        format: 'mp4'
      }).then(composition =>{      
        console.log("Created Composition with SID=" + composition.sid); // This works properly
        cid=composition.sid;
        pushCompositionId(composition.sid,response); // I want to call this function here
      });
});

否则,您可以使用wait/async返回类似同步的结果

是否可以包含完整的服务器端文件?为了了解其他函数的声明位置。jQuery包含在您的服务器端?我已经编辑并包含了整个服务器端代码您确定没有调用函数iinside pushCompisitionId吗?或者问题是,它是在您向客户端发送响应后执行的?调用该函数。如果我删除ajax部分并简单地放置一个console.log(compositionid),那么我会在控制台中看到正确的输出。我认为问题在于向客户端发送响应的时间。这不需要等到那时才能解决。为什么要投否决票?我没有投否决票。顺便说一句,我会检查你的解决方案。到目前为止,我一直在显式编写响应。sendI现在已成功重定向到pushCompositionId。但是ajax仍然没有正确执行。当我将它包含在try-catch块中时,我收到了这个错误-TypeError:jquery.ajax不是一个函数。我已将jQuery包含在我的文件中。我不明白。jQuery不能像在客户端那样使用(您可以在NodeJS中使用本机网络模块管理请求)。顺便说一句,我更正了我的答案,以包含正确的jQuery导入(您将需要其他模块,并模拟浏览器窗口以使其工作)是的,我只是在其他线程中阅读。曾经使用过jsdom,现在可以使用了。谢谢你的帮助!:)