在另一个文件中调用数组中的 promise

huangapple go评论80阅读模式
英文:

Calling a promise from within an array on a seperate file

问题

以下是已翻译的内容:

我是初学JavaScript编程的我正在使用GitHub Codespaces来编写代码同时也在使用Firefox浏览器
基础知识我正在逐渐理解但这个问题让我感到困惑我试图将事件的代码放入不同的文件中使用一种结构以便我可以为不同的事件创建更多的文件

这是我的 `App.js` 文件
```javascript
import './App.css';

import { events } from './events.js';

const files = [
  events,
]

function imports(files) {
  let return_info = []
  for (let file in files) {
    if (files.core) {
      return_info[return_info.length + 1] = files.core()
    }
  }
  return return_info
}

function App() {
  return (
    <div className="App">
      <header className="App-header">
        <p>
          GitHub Codespaces <span className="heart">♥️</span> React
        </p>
        <p className="small">
          Edit <code>src/App.js</code> and save to reload.
        </p>
        {imports(files)}
        <p>
          <a
            className="App-link"
            href="https://reactjs.org"
            target="_blank"
            rel="noopener noreferrer"
          >
            Learn React
          </a>
        </p>
      </header>
    </div>
  );
}

function eventlisting() {
  for (let file in files) {
    if (files.subscribe) {
      for (let event in files.subscribe) {
        console.debug(`adding event ${event}, with reacton; ${files[file].subscribe[event].reacton} and action of ${files[file].subscribe[event].action}`)
        window.addEventListener(files.subscribe[event].reacton, files.subscribe[event].action)
      }
    }
  }
}

eventlisting()

export default App;

这是我尝试将事件放入的文件,命名为 events.js

function errorlog(string) {
    if (typeof(string) === "string") {
        console.error(`An error has occured\n${string}`)
    } else {
        console.error(`An error has occured. And no information was given.`)
    }
}

function window_size_string() {
    return new Promise((resolve, reject) => {
        var windowHeight = window.innerHeight;
        var windowWidth = window.innerWidth;
        if (typeof(windowHeight) === "number" && typeof(windowWidth) === "number") {
            resolve (
                `${windowHeight} by ${windowWidth}`
            )
        } else {
            reject(`types found, ${typeof(windowHeight)} and ${typeof(windowWidth)}`)
        }
    })
}

async function update_window_size() {
  const text = document.getElementById("window_size")
  await window_size_string()
  .then(string => {text.firstChild.nodeValue = string
    })
  .catch(string => errorlog(string));
}


var events = []

events.core = function() {
    return (
        <p id="window_size" className="small">
            空白文本
        </p>
    )
}

events.base = function() {
    update_window_size().catch(string => errorlog(string))
}

events.subscribe = [
    {reacton: "resize", action: update_window_size().catch(string => errorlog(string))}
]

export default { events }
export { events }

我期望的是当我加载网站时,能看到一行带有 "空白文本" 的文字,但一旦屏幕大小发生变化,它就会更改为其他内容。

我尝试过在 events.js 中创建不同版本的 events.subscribe。匿名函数方式:

events.subscribe = [
    {reacton: "resize", action: {function() {update_window_size().catch(string => errorlog(string))}}}
]

不将其作为函数调用:

events.subscribe = [
    {reacton: "resize", action: update_window_size}
]

但问题似乎并不在这里,所以我将其改回了我之前的方式。然后我改变了 app.js 中的 eventlisting() 函数。

我首先尝试将 action 作为函数调用:

function eventlisting() {
  for (let file in files) {
    if (files[file].subscribe) {
      for (let event in files[file].subscribe) {
        console.debug(`adding event ${event}, with reacton; ${files[file].subscribe[event].reacton} and action of ${files[file].subscribe[event].action}`)
        window.addEventListener(files[file].subscribe[event].reacton, files[file].subscribe[event].action())
      }
    }
  }
}

这在某种程度上有效,如果网站在我进行这个更改之前已经运行。但只能运行一次。然后我尝试在这里创建匿名函数,但也没有成功:

function eventlisting() {
  for (let file in files) {
    if (files[file].subscribe) {
      for (let event in files[file].subscribe) {
        console.debug(`adding event ${event}, with reacton; ${files[file].subscribe[event].reacton} and action of ${files[file].subscribe[event].action}`)
        window.addEventListener(files[file].subscribe[event].reacton,  function() {files[file].subscribe[event].action();})
      }
    }
  }
}

我不确定我是否采取了愚蠢的方式来解决这个问题,是否犯了初学者的错误,或者我正在尝试一些不应该做的事情。我希望能够提供解决这个问题的见解。

英文:

I am new to programming in javascript and I am using github codespaces .js thing for it. As well as the firefox browser.
The basics I am starting to understand but this problem just baffles me. I am trying to put the code for events into a different file. With a structure so I can just make more files for different events.

This is my App.js file

import &#39;./App.css&#39;;

import {events} from &#39;./events.js&#39;;

const files = [
  events,
]

function imports(files) {
  let return_info = []
  for (let file in files) {
    if (files[file].core) {
      return_info[return_info.length+1] = files[file].core()
    }  
  }
  return return_info
}

function App() {
  return (
    &lt;div className=&quot;App&quot;&gt;
      &lt;header className=&quot;App-header&quot;&gt;
        &lt;p&gt;
          GitHub Codespaces &lt;span className=&quot;heart&quot;&gt;♥️&lt;/span&gt; React
        &lt;/p&gt;
        &lt;p className=&quot;small&quot;&gt;
          Edit &lt;code&gt;src/App.js&lt;/code&gt; and save to reload.
        &lt;/p&gt;
        {imports(files)}
        &lt;p&gt;
          &lt;a
            className=&quot;App-link&quot;
            href=&quot;https://reactjs.org&quot;
            target=&quot;_blank&quot;
            rel=&quot;noopener noreferrer&quot;
          &gt;
            Learn React
          &lt;/a&gt;
        &lt;/p&gt;
      &lt;/header&gt;
    &lt;/div&gt;
  );
}

function eventlisting() {
  for (let file in files) {
    if (files[file].subscribe) {
      for (let event in files[file].subscribe) {
        console.debug(`adding event ${event}, with reacton; ${files[file].subscribe[event].reacton} and action of ${files[file].subscribe[event].action}`)
        window.addEventListener(files[file].subscribe[event].reacton, files[file].subscribe[event].action)
      }
    }
  }
}

eventlisting()

export default App;

And this is the file I am trying to get my events in. Named events.js


function errorlog(string) {
    if (typeof(string) === &quot;string&quot;) {
        console.error(`An error has occured\n${string}`)
    } else {
        console.error(`An error has occured. And no information was given.`)
    }
}

function window_size_string() {
    return new Promise((resolve, reject) =&gt; {
        var windowHeight = window.innerHeight;
        var windowWidth = window.innerWidth;
        if (typeof(windowHeight) === &quot;number&quot; &amp;&amp; typeof(windowWidth) === &quot;number&quot;) {
            resolve (
                `${windowHeight} by ${windowWidth}`
            )
        } else {
            reject(`types found, ${typeof(windowHeight)} and ${typeof(windowWidth)}`)
        }
    })
}

async function update_window_size() {
  const text = document.getElementById(&quot;window_size&quot;)
  await window_size_string()
  .then(string =&gt; {text.firstChild.nodeValue = string
    })
  .catch(string =&gt; errorlog(string));
}


var events = []

events.core = function() {
    return (
        &lt;p id=&quot;window_size&quot; className=&quot;small&quot;&gt;
            blank text
        &lt;/p&gt;
    )
}

events.base = function() {
    update_window_size().catch(string =&gt; errorlog(string))
}

events.subscribe = [
    {reacton: &quot;resize&quot;, action: update_window_size().catch(string =&gt; errorlog(string))}
]

export default {events}
export {events}

The thing I expect to happen is that when I load the site I see a line with "blank text" but the moment the screen resizes it changes the text to something else.

I have tried to make different versions of the events.subscribe thingy in events.js.
An anonymous function;

events.subscribe = [
    {reacton: &quot;resize&quot;, action: {function() {update_window_size().catch(string =&gt; errorlog(string))}}}
]

Not calling it as a function.

events.subscribe = [
    {reacton: &quot;resize&quot;, action: update_window_size}
]

But the problem did not seem to lay here, so I changed it back to what I had. So I changed the eventlisting() function in app.js.
My fist attempt was calling the action as a function.

function eventlisting() {
  for (let file in files) {
    if (files[file].subscribe) {
      for (let event in files[file].subscribe) {
        console.debug(`adding event ${event}, with reacton; ${files[file].subscribe[event].reacton} and action of ${files[file].subscribe[event].action}`)
        window.addEventListener(files[file].subscribe[event].reacton, files[file].subscribe[event].action())
      }
    }
  }
}

This kinda works, if the site is already running before I make this change. But only once.
Then I tried to make an anonymous function here but that also did not work.

function eventlisting() {
  for (let file in files) {
    if (files[file].subscribe) {
      for (let event in files[file].subscribe) {
        console.debug(`adding event ${event}, with reacton; ${files[file].subscribe[event].reacton} and action of ${files[file].subscribe[event].action}`)
        window.addEventListener(files[file].subscribe[event].reacton,  function() {files[file].subscribe[event].action();})
      }
    }
  }
}

I am not sure if I am using a stupid way to go about this. Making a rookie mistake. Or I am trying something that should not be done. I hope for insights on how to solve this problem.

答案1

得分: 0

我找到了我的问题。

我需要调用我已经制作的函数的引用,而不是函数的解决方案。意思是我需要这段代码:

events.subscribe = [
    {reacton: &quot;resize&quot;, action: update_window_size}
]

然后在另一端,我实际上需要调用要发送的函数。
通过

function eventlisting() {
  for (let file in files) {
    if (files[file].subscribe) {
      for (let event in files[file].subscribe) {
        console.debug(`adding event ${event}, with reacton; ${files[file].subscribe[event].reacton} and action of ${files[file].subscribe[event].action}`)
        window.addEventListener(files[file].subscribe[event].reacton,  function() {files[file].subscribe[event].action();})
      }
    }
  }
}

或通过;

function eventlisting() {
  for (let file in files) {
    if (files[file].subscribe) {
      for (let event in files[file].subscribe) {
        console.debug(`adding event ${event}, with reacton; ${files[file].subscribe[event].reacton} and action of ${files[file].subscribe[event].action}`)
        window.addEventListener(files[file].subscribe[event].reacton, files[file].subscribe[event].action())
      }
    }
  }
}

我离解决方案很接近,但还没有完全到位。

英文:

I found my problem.

I needed to call a reference to the function I had made, and not the solution of the function. Meaning I needed this code;

events.subscribe = [
    {reacton: &quot;resize&quot;, action: update_window_size}
]

Then on the other end I needed to actually call the function to be send through.
Either via

function eventlisting() {
  for (let file in files) {
    if (files[file].subscribe) {
      for (let event in files[file].subscribe) {
        console.debug(`adding event ${event}, with reacton; ${files[file].subscribe[event].reacton} and action of ${files[file].subscribe[event].action}`)
        window.addEventListener(files[file].subscribe[event].reacton,  function() {files[file].subscribe[event].action();})
      }
    }
  }
}

Or via;

function eventlisting() {
  for (let file in files) {
    if (files[file].subscribe) {
      for (let event in files[file].subscribe) {
        console.debug(`adding event ${event}, with reacton; ${files[file].subscribe[event].reacton} and action of ${files[file].subscribe[event].action}`)
        window.addEventListener(files[file].subscribe[event].reacton, files[file].subscribe[event].action())
      }
    }
  }
}

I was very close to the solution but not quite there yet.

huangapple
  • 本文由 发表于 2023年6月19日 18:11:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/76505627.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定