·深蓝

文章 评论 浏览 27

·深蓝 2025-02-20 16:44:03

这是我们在JavaScript的“奥秘”挣扎时面临的一个非常普遍的问题。让我尝试今天揭开这个谜。

让我们从一个简单的JavaScript函数开始:

function foo(){
    // Do something
    return 'wohoo';
}

let bar = foo(); // 'bar' is 'wohoo' here

这是一个简单的同步函数调用(在下一个代码的每行都“完成其作业”的“完成”),结果与预期的结果相同。

现在,让我们通过在函数中引入一点延迟来添加一些扭曲,以使所有代码都不是“完成”的。因此,它将模仿该功能的异步行为:

function foo(){
    setTimeout( ()=> {
        return 'wohoo';
   }, 1000)
}

let bar = foo() // 'bar' is undefined here

因此您就去了;延迟刚刚打破了我们期望的功能!但是到底发生了什么?好吧,如果您查看代码,这实际上是合乎逻辑的。

函数 foo(),在执行后,返回什么都没有(因此返回的值是 undefined ),但它确实启动了一个计时器,该计时器在1秒钟后执行函数以返回'哇。但是,如您所见,分配给bar的值是Foo()的立即返回的内容,即,即 undefined

那么,我们如何解决这个问题


承诺实际上是关于它的含义:这意味着功能可以确保您提供将来的任何输出。因此,让我们在上面的小问题上查看它的行动:

function foo(){
   return new Promise((resolve, reject) => { // I want foo() to PROMISE me something
    setTimeout ( function(){
      // Promise is RESOLVED, when the execution reaches this line of code
       resolve('wohoo') // After 1 second, RESOLVE the promise with value 'wohoo'
    }, 1000 )
  })
}

let bar;
foo().then( res => {
    bar = res;
    console.log(bar) // Will print 'wohoo'
});

因此,摘要是 - 处理类似基于AJAX的呼叫等异步函数,您可以使用承诺来 resolve> resolve 该值(哪个值(您打算返回)。因此,简而言之,您解决值,而不是返回,在异步函数中。

除了使用然后/catch 与Promises合作之外,更新(ASYNC/等待的承诺)

除了使用之外,还有另一种方法。这个想法是识别异步函数,然后等待承诺在移至下一行代码之前解决。它仍然只是引擎盖下的承诺,但采用不同的句法方法。为了使事情变得更清晰,您可以在下面找到一个比较:

然后/捕获版本:

function saveUsers(){
     getUsers()
      .then(users => {
         saveSomewhere(users);
      })
      .catch(err => {
          console.error(err);
       })
 }

async/等待版本:

  async function saveUsers(){
     try{
        let users = await getUsers()
        saveSomewhere(users);
     }
     catch(err){
        console.error(err);
     }
  }

It's a very common issue we face while struggling with the 'mysteries' of JavaScript. Let me try demystifying this mystery today.

Let's start with a simple JavaScript function:

function foo(){
    // Do something
    return 'wohoo';
}

let bar = foo(); // 'bar' is 'wohoo' here

That's a simple synchronous function call (where each line of code is 'finished with its job' before the next one in sequence), and the result is same as expected.

Now let's add a bit of twist, by introducing a little delay in our function, so that all lines of code are not 'finished' in sequence. Thus, it will emulate the asynchronous behavior of the function:

function foo(){
    setTimeout( ()=> {
        return 'wohoo';
   }, 1000)
}

let bar = foo() // 'bar' is undefined here

So there you go; that delay just broke the functionality we expected! But what exactly happened? Well, it's actually pretty logical if you look at the code.

The function foo(), upon execution, returns nothing (thus returned value is undefined), but it does start a timer, which executes a function after 1 second to return 'wohoo'. But as you can see, the value that's assigned to bar is the immediately returned stuff from foo(), which is nothing, i.e., just undefined.

So, how do we tackle this issue?

Let's ask our function for a promise.
Promise is really about what it means: it means that the function guarantees you to provide with any output it gets in future. So let's see it in action for our little problem above:

function foo(){
   return new Promise((resolve, reject) => { // I want foo() to PROMISE me something
    setTimeout ( function(){
      // Promise is RESOLVED, when the execution reaches this line of code
       resolve('wohoo') // After 1 second, RESOLVE the promise with value 'wohoo'
    }, 1000 )
  })
}

let bar;
foo().then( res => {
    bar = res;
    console.log(bar) // Will print 'wohoo'
});

Thus, the summary is - to tackle the asynchronous functions like Ajax-based calls, etc., you can use a promise to resolve the value (which you intend to return). Thus, in short you resolve value instead of returning, in asynchronous functions.

UPDATE (Promises with async/await)

Apart from using then/catch to work with promises, there exists one more approach. The idea is to recognize an asynchronous function and then wait for the promises to resolve, before moving to the next line of code. It's still just the promises under the hood, but with a different syntactical approach. To make things clearer, you can find a comparison below:

then/catch version:

function saveUsers(){
     getUsers()
      .then(users => {
         saveSomewhere(users);
      })
      .catch(err => {
          console.error(err);
       })
 }

async/await version:

  async function saveUsers(){
     try{
        let users = await getUsers()
        saveSomewhere(users);
     }
     catch(err){
        console.error(err);
     }
  }

如何从异步电话中返回响应?

·深蓝 2025-02-20 15:52:58

更好的方法是使用自定义这样的功能:

var ctx = document.getElementById("canvas").getContext("2d");

window.myBar = new Chart(ctx, {
  type: 'pie',
  data: {
    labels: ['red - some other text that appears after', 'blue - some other text that appears after', 'green - some other text that appears after', 'orange - some other text that appears after'],
    datasets: [{
      data: [4, 2, 10, 3],
      backgroundColor: ['red', 'blue', 'green', 'orange'],
    }],
  },
  options: {
    responsive: true,
    legend: {
      labels: {
        generateLabels: function(chart) {
          const data = chart.data;
          if (data.labels.length && data.datasets.length) {
            return data.labels.map(function(label, i) {
              const meta = chart.getDatasetMeta(0);
              const style = meta.controller.getStyle(i);

              return {
                text: label.split(' - ')[0],
                fillStyle: style.backgroundColor,
                strokeStyle: style.borderColor,
                lineWidth: style.borderWidth,
                hidden: isNaN(data.datasets[0].data[i]) || meta.data[i].hidden,

                // Extra data used for toggling the correct item
                index: i
              };
            });
          }
          return [];
        }
      }
    }
  },
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.bundle.js"></script>

<div style="width: 100%">
  <canvas id="canvas"></canvas>
</div>

A better approach would be to use a custom generateLabels function like so:

var ctx = document.getElementById("canvas").getContext("2d");

window.myBar = new Chart(ctx, {
  type: 'pie',
  data: {
    labels: ['red - some other text that appears after', 'blue - some other text that appears after', 'green - some other text that appears after', 'orange - some other text that appears after'],
    datasets: [{
      data: [4, 2, 10, 3],
      backgroundColor: ['red', 'blue', 'green', 'orange'],
    }],
  },
  options: {
    responsive: true,
    legend: {
      labels: {
        generateLabels: function(chart) {
          const data = chart.data;
          if (data.labels.length && data.datasets.length) {
            return data.labels.map(function(label, i) {
              const meta = chart.getDatasetMeta(0);
              const style = meta.controller.getStyle(i);

              return {
                text: label.split(' - ')[0],
                fillStyle: style.backgroundColor,
                strokeStyle: style.borderColor,
                lineWidth: style.borderWidth,
                hidden: isNaN(data.datasets[0].data[i]) || meta.data[i].hidden,

                // Extra data used for toggling the correct item
                index: i
              };
            });
          }
          return [];
        }
      }
    }
  },
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.bundle.js"></script>

<div style="width: 100%">
  <canvas id="canvas"></canvas>
</div>

在图表中更改图例文字JS引起问题

·深蓝 2025-02-19 17:29:51

Openssl 具有称为 legacy 的密钥算法提供商。只需尝试:

openssl pkcs12 -in mycert.p12 -legacy -nodes

openssl has a key algorithm provider called legacy. Just try with:

openssl pkcs12 -in mycert.p12 -legacy -nodes

将旧样式.p12转换为.pem(不支持算法RC2-40-CBC)

·深蓝 2025-02-19 15:21:45

因为您使用上层版本PG_BASEBACKUP二进制文件,并且服务器版本低于此PG_BASEBACKUP

because you use the upper version pg_basebackup binary,and your server version is lower than this pg_basebackup

PostgreSQL流式复制 - 无效连接选项“ SSLSNI”

·深蓝 2025-02-19 10:55:10

我认为您的问题是(或应该是

I think your question is (or should be ????): "How do I tell TypeScript that my function is of type Handle?".

I think the simplest way would be to create a variable out of the function so you can easily type it.

export const handle: Handle = async function ({ event, resolve }) {
  console.log(event.locals);
}

Notice that you don't need to type event or resolve separately, TS already knows about your function's argument and return type. It will flag your existing implementation because it's not returning a MaybePromise<Response>

如何在钩子中添加TypeScript到Sveltekit句柄功能?

·深蓝 2025-02-19 10:14:59

你是这样的吗?您需要使用JS

在服务器上提交设置值

window.addEventListener("DOMContentLoaded", () => {
  document.getElementById("form1").submit();
})
<form id="form1" action="file.php" method="POST">
  <textarea type="text" name="stream" style="width:80%;" rows="7" cols="40">test</textarea>
  <br />
  <label for="number"><span style="font-size: 30pt;">number of results:</span></label>
  <input type="text" name="number" style="width:70px; margin: 50pt;" value="5">
  <br />
  <input type="submit" value="Submit form">
</form>

或在客户端设置值

window.addEventListener("DOMContentLoaded", () => {
  document.querySelector("[name=stream]").value="test";
  document.querySelector("[name=number]").value="5";
  document.getElementById("form1").submit();
})
<form id="form1" action="file.php" method="POST">
  <textarea type="text" name="stream" style="width:80%;" rows="7" cols="40"></textarea>
  <br />
  <label for="number"><span style="font-size: 30pt;">number of results:</span></label>
  <input type="text" name="number" style="width:70px; margin: 50pt; ">
  <br />
  <input type="submit" value="Submit form">
</form>

You mean like this? You will need to use JS to submit

Set values on server

window.addEventListener("DOMContentLoaded", () => {
  document.getElementById("form1").submit();
})
<form id="form1" action="file.php" method="POST">
  <textarea type="text" name="stream" style="width:80%;" rows="7" cols="40">test</textarea>
  <br />
  <label for="number"><span style="font-size: 30pt;">number of results:</span></label>
  <input type="text" name="number" style="width:70px; margin: 50pt;" value="5">
  <br />
  <input type="submit" value="Submit form">
</form>

or set values on client

window.addEventListener("DOMContentLoaded", () => {
  document.querySelector("[name=stream]").value="test";
  document.querySelector("[name=number]").value="5";
  document.getElementById("form1").submit();
})
<form id="form1" action="file.php" method="POST">
  <textarea type="text" name="stream" style="width:80%;" rows="7" cols="40"></textarea>
  <br />
  <label for="number"><span style="font-size: 30pt;">number of results:</span></label>
  <input type="text" name="number" style="width:70px; margin: 50pt; ">
  <br />
  <input type="submit" value="Submit form">
</form>

自动填充表单字段,html

·深蓝 2025-02-18 23:17:16

您可以使用 serialize_map()

impl Serialize for FooBarList {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        let item_count = self.items.len();

        let mut struct_ser = serializer.serialize_map(Some(1 + 2 * item_count))?;

        for (i, item) in (&self.items).into_iter().enumerate() {
            struct_ser.serialize_entry(&format!("foo{}", i + 1), &item.foo)?;
            struct_ser.serialize_entry(&format!("bar{}", i + 1), &item.bar)?;
        }

        struct_ser.serialize_entry("name", &self.name)?;

        struct_ser.end()
    }
}

不过,您不能以这种方式为结构命名。

You can serialize it as a map using serialize_map():

impl Serialize for FooBarList {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        let item_count = self.items.len();

        let mut struct_ser = serializer.serialize_map(Some(1 + 2 * item_count))?;

        for (i, item) in (&self.items).into_iter().enumerate() {
            struct_ser.serialize_entry(&format!("foo{}", i + 1), &item.foo)?;
            struct_ser.serialize_entry(&format!("bar{}", i + 1), &item.bar)?;
        }

        struct_ser.serialize_entry("name", &self.name)?;

        struct_ser.end()
    }
}

You can't give a name to the struct in this way, though.

我如何将结构序列化为使用Serde在Rust中具有动态键的格式

·深蓝 2025-02-18 19:39:52

Google的官方建议是鼓励您的用户切换到A a>

对于2022年11月以后的用户体验,我认为您可以联系 Google Map Platform Platform支持团队详情。

参考链接:

The official suggestion from Google is encourage your users to switch to a supported browser.

For the user experience after November 2022, I think you can contact Google Maps Platform Support Team for detailed information.

Reference link: https://groups.google.com/g/google-maps-js-api-v3-notify/c/l3mdkZ5JyDg/m/Ml84u2nvBgAJ

Google地图支持Internet Explorer 11 v3.47 2022年11月之后

·深蓝 2025-02-18 19:04:47

将其更改

onRetryAsync: (e, timeSpan, retryCount, context) => { 
   this.logger.LogInfo($"Request failed with {result.Result.StatusCode}. Waiting 
    {timeSpan} before next retry. Retry attempt {retryCount}"); 
   return Task.CompletedTask; 
});`

为OnReTryAsync期望的任务返回类型

Change it to

onRetryAsync: (e, timeSpan, retryCount, context) => { 
   this.logger.LogInfo(
quot;Request failed with {result.Result.StatusCode}. Waiting 
    {timeSpan} before next retry. Retry attempt {retryCount}"); 
   return Task.CompletedTask; 
});`

as onRetryAsync expects a Task return type

在使用Polly重试之前,登录的正确方法是什么

·深蓝 2025-02-18 05:19:14

这是我问题的答案

        <div>

            {Object.keys(collection).length > 0 ? <div>
                <h1>{collection.name}</h1>
                <p>{collection.description}</p>
                {collection.collectionItemsID.map(function (itemID) {
                    return <a href={`/${itemID}`}>{itemID}</a>
                })}
            </div> : <p>Loading...</p>}
        </div>

This is the answer of my question

        <div>

            {Object.keys(collection).length > 0 ? <div>
                <h1>{collection.name}</h1>
                <p>{collection.description}</p>
                {collection.collectionItemsID.map(function (itemID) {
                    return <a href={`/${itemID}`}>{itemID}</a>
                })}
            </div> : <p>Loading...</p>}
        </div>

ReactJS阵列在对象中

·深蓝 2025-02-18 01:36:43

使用: - utilities.formatdate(new Date(),session.getTimeZone,“ dd/mm/yyyy”)

Use :- Utilities.formatDate(new Date(),Session.getTimeZone,"dd/MM/yyyy")

如何使用Google Apps脚本转换选定单元格的日期格式

·深蓝 2025-02-17 22:58:23

如果您想在JS中执行操作而不启动服务器,则传统上被称为脚本。脚本通常以按需方式运行,而不是像服务器一样不断运行。如果创建一个名为 read-file.js 的新脚本,则可以通过在终端中运行 node read-file.js 来运行脚本。

要读取没有服务器的静态文件,您可以使用以下脚本:

const { readFile } = require('fs');
const { join } = require('path');

readFile(join(__dirname, 'test.html'), 'utf8', (err, data) => {
    if (err) {
        console.log(err);
    }
    
    console.log(data);
});

If you would like to perform operations in JS without starting up a server, this is traditionally known as a script. Scripts are usually run in an on-demand fashion rather than constantly running like a server. If you create a new script named read-file.js, you could run the script by running node read-file.js in your terminal.

To read a static file without a server, you could use the following script:

const { readFile } = require('fs');
const { join } = require('path');

readFile(join(__dirname, 'test.html'), 'utf8', (err, data) => {
    if (err) {
        console.log(err);
    }
    
    console.log(data);
});

我可以将启动节点服务器记录文件或数据记录吗?

·深蓝 2025-02-17 20:58:40

Stylelint 14.x和Stylelint-Config-airbnb插件之间存在兼容性错误。

There is a compatibility error between Stylelint 14.x and the stylelint-config-airbnb plugin. https://issuemode.com/issues/airbnb/css/10818973

StyleLint&#x27;未知规则声明-property-value-black-lacklist&#x27;每个CSS文件的错误

·深蓝 2025-02-17 10:38:13

您可以做一个不分散的,然后旋转该对象。这只是一个猜测,因为我不知道您想要最终输出的外观,但也许...

SELECT *
FROM
    (select PriceName, Portfolio, benchmark, 
       CONVERT(VARCHAR(20), PriceVal) AS [PriceVal],
       CONVERT(VARCHAR(20), PriceName_Change) AS [PriceName_Change]from temptable) 
as PVT
UNPIVOT
(
  Item for Items in (PriceVal, PriceName_Change)
) AS unpvt
GO

“在此处输入映像”

You could do an UNPIVOT and then PIVOT that object. This is just a guess, because I don't know what you want the final output to look like, but maybe...

SELECT *
FROM
    (select PriceName, Portfolio, benchmark, 
       CONVERT(VARCHAR(20), PriceVal) AS [PriceVal],
       CONVERT(VARCHAR(20), PriceName_Change) AS [PriceName_Change]from temptable) 
as PVT
UNPIVOT
(
  Item for Items in (PriceVal, PriceName_Change)
) AS unpvt
GO

enter image description here

如何进行多个枢轴

·深蓝 2025-02-17 02:09:25

是的,我只需要等待和希望!

大约2个小时后,一切正常开始工作。

Yup, I just had to wait and hope!

After about 2 hours, everything started working back as normal.

备份固定在发现设备上

更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

更多

友情链接

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文