簡體   English   中英

Function 返回從 socket.on (socket.io) 得到的結果

[英]Function return the result getting from an socket.on (socket.io)

我是 socket.io 的新手。 我在處理 socket.on 的異步時遇到了一些麻煩,想知道是否有解決方法或某種方法可以為 socket.on 制作整個 function 塊

我正在開發一個 API 來從 MongoDB 獲取數據。 並在反應前端調用那些 API。 我最近正在嘗試執行以下操作:

// frontend (onClick function)
const handleOnClick = () => {
    const data = api();
    // do the work
}


// API
const api = () => {
var value;

    // ask for data
    socket.emit("ask-for-data");

    // get respond from database
    socket.on("get-response", (data) => {
        value = data;                       //<- value is correct right here
    });

    //respond from API
    return { value };                       //<- value is undefined

我想讓整個 function 返回 socket.io 獲取的數據。 但是,我嘗試將 async-await 添加到 API function 中,結果沒有用。

// frontend (onClick function)
const handleOnClick = async () => {
    const data = await api();
    // do the work
}


// API
const api = async () => {
var value;

    // ask for data
    socket.emit("ask-for-data");

    // get respond from database
    await socket.on("get-response", (data) => {
        value = data;                       //<- value is correct right here
    });

    //respond from API
    return { value };                       //<- value is undefined

那么有什么方法可以確保我可以返回從 socket.on 獲得的值? I know that socket.on is handle as an asynchronous function and the API function will return way before the socket io finishes their tasks. 順便說一句,API 和 handleOnClick 存儲在不同的 js 文件中。 謝謝你的時間!

socket.on()不是異步的:這意味着執行流程將繼續進行,而無需等待任何get-response事件,並且您的value變量將是undefined

嘗試將您的api function 包裝在Promise中,當您使用get-response時,它會解決,例如:

const api = function() {
  return new Promise(function(resolve, reject) {
    socket.emit("ask-for-data");
    socket.on("get-response", (data) => {
      resolve(data);
    })
  });
}

接着

const data = await api();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM