使用套接字时返回承诺

时间:2018-12-27 15:04:11

标签: javascript sockets socket.io promise async-await

我试图从套接字获取一个值,然后在异步函数中返回它。我已经阅读并尝试过阅读有关SO和其他地方的更多内容。尽管存在从“ socket.on”返回的数据,并且已填充“ response”,但此方法的值未在该方法中返回,并且返回了一个空对象。

请不要将其标记为重复项,因为我在此处尝试了许多有关promise,asyn函数,socket,websockets等的线程,但无法解决。

   export function performSearchTemp(options: ISearchEntityRequest, callingMethod?: string): Promise<IActionResponse<any>> {
        const baseSearchRequest = Object.assign({}, BASE_SEARCH_REQUEST, options);
        let response = <IActionResponse<ISearchEntityResponse>>{};

            const io = require('socket.io-client');
            const socket = io.connect();

            socket.on('connect', async function (data) {

                socket.on('fetchShareClasses', async function (searchResponse) {

                        searchResponse = await fetch(ENDPOINTS.fund.searchEntity, generateRequest('POST', baseSearchRequest))
                            .then(function (a) {
                                return a.json(); // call the json method on the response to get JSON
                            })
                            .then(function (json) {
                                socket.emit('fetchShareClasses', JSON.stringify(json));
                            });
                    }

                    searchResponse = 
                    JSON.stringify(searchResponse);

                    **//THIS HAS THE CORRECT DATA**
                    response = JSON.parse(searchResponse);
                    console.log("​response", response)

                });
            });
            **//THIS RETURNS an EMPTY OBJECT TO THE CALLING METHOD**
            return Promise.resolve(response);

    }

真的很感谢我的建议,因为我花了很多时间解决这个问题。

1 个答案:

答案 0 :(得分:1)

我认为,如果将套接字包装在promise中并解决结果,它将起作用:

 export function performSearchTemp(options: ISearchEntityRequest, callingMethod?: string): Promise<IActionResponse<any>> {
        const baseSearchRequest = Object.assign({}, BASE_SEARCH_REQUEST, options);
        let response = <IActionResponse<ISearchEntityResponse>>{};

        const io = require('socket.io-client');
        const socket = io.connect();
        return new Promise( (resolve) => {
            socket.on('connect', async function (data) {

                socket.emit('fetchShareClasses', 'init');
                socket.on('fetchShareClasses', async function (searchResponse) {

                    if (searchResponse === 'init') {
                        searchResponse = await fetch(ENDPOINTS.fund.searchEntity, generateRequest('POST', baseSearchRequest))
                            .then(function (a) {
                                return a.json(); // call the json method on the response to get JSON
                            })
                            .then(function (json) {
                                socket.emit('fetchShareClasses', JSON.stringify(json));
                            });
                        resolve(searchResponse);
                    }
                    else {
                    console.log("test searchResponse ORCHESTRATE ::");
                        searchResponse = 
                        JSON.stringify(searchResponse);

                        **//THIS HAS THE CORRECT DATA**
                        response = JSON.parse(searchResponse);
                        console.log("​response", response)
                        resolve(response);
                    }
                });
            });
        });
    }