JS Promise函数调用返回对象

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

JS Promise function call that returns object

问题

I have a async fetch function that waits 2 seconds and returns an object:

  1. async function fetch() {
  2. var object;
  3. await setTimeout(() => { object = { name: 'User', data: 'API Data' } }, 2000);
  4. return object;
  5. }

I want to display the object when the initialization is completely done (after 2 seconds):

  1. fetch().then((val) => {
  2. console.log("DONE!");
  3. console.log(val.name);
  4. }).catch((err) => {
  5. console.log("ERROR!");
  6. console.log(err);
  7. });

The code prints both DONE and ERROR Cannot read properties of undefined (reading 'name').

I have tried with Promise, no luck:

  1. let promise = new Promise((resolve, reject) => {
  2. let request = fetch();
  3. if (request !== undefined)
  4. resolve(request);
  5. else
  6. reject(request);
  7. }).then((val) => {
  8. console.log(val);
  9. });

How can I properly check that fetch() has returned a value before printing without changing the inside of the function? I can delete the async and await in it but I am unable to edit it (i.e. adding a Promise inside).

英文:

I have a async fetch function that waits 2 seconds and returns a object:

  1. async function fetch() {
  2. var object;
  3. await setTimeout(() => { object = { name: 'User', data: 'API Data' } }, 2000);
  4. return object;
  5. }

I want to display the object when the initialization is completely done (after 2 seconds)

  1. fetch().then((val) => {
  2. console.log("DONE!");
  3. console.log(val.name);
  4. }).catch((err) => {
  5. console.log("ERROR!");
  6. console.log(err);
  7. });

The code prints both DONE and ERROR Cannot read properties of undefined (reading 'name')

I have tried with Promise, no luck

  1. let promise = new Promise((resolve, reject) => {
  2. let request = fetch();
  3. if (request !== undefined)
  4. resolve(request);
  5. else
  6. reject(request);
  7. }).then((val) => {
  8. console.log(val);
  9. });

How can I properly check that fetch() has returned a value before printing without changing the inside of the function. I can delete the async and await in it but I am unable to edit it (I.E. adding a Promise inside)

答案1

得分: 1

基于要求,

> 我可以删除其中的async和await(在fetch函数中),但我无法编辑它(即添加一个Promise)

我唯一能想到的方法是覆盖window.setTimeout函数,使其返回一个Promise。这样你就可以等待它,而不需要修改你的fetch函数。

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const oldTimeout = window.setTimeout;
window.setTimeout = (fn, ms) => {
return new Promise((resolve, reject) => {
oldTimeout(() => {
fn();
resolve();
}, ms);
});
};

async function fetch() {
var object;
await setTimeout(() => {
object = { name: "User", data: "API Data" };
}, 2000);
return object;
}

fetch()
.then((val) => {
console.log("DONE!");
console.log(val.name);
})
.catch((err) => {
console.log("ERROR!");
console.log(err);
});

<!-- end snippet -->

注意:对于没有这个要求的人,请使用其他答案或查看await setTimeout is not synchronously waiting以获取更多详细信息/解释。这种覆盖可能会让人感到困惑,因为每个人都希望常见和众所周知的函数在文档中描述的方式中运行。

英文:

Based on requirement

> I can delete the async and await in it (fetch function) but I am unable to edit it (I.E. adding a Promise inside)

The only way I see is to override window.setTimeout function to make it to return a promise. That way you will be able to await it and there will be no need to modify your fetch function.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

  1. const oldTimeout = window.setTimeout;
  2. window.setTimeout = (fn, ms) =&gt; {
  3. return new Promise((resolve, reject) =&gt; {
  4. oldTimeout(() =&gt; {
  5. fn();
  6. resolve();
  7. }, ms);
  8. });
  9. };
  10. async function fetch() {
  11. var object;
  12. await setTimeout(() =&gt; {
  13. object = { name: &quot;User&quot;, data: &quot;API Data&quot; };
  14. }, 2000);
  15. return object;
  16. }
  17. fetch()
  18. .then((val) =&gt; {
  19. console.log(&quot;DONE!&quot;);
  20. console.log(val.name);
  21. })
  22. .catch((err) =&gt; {
  23. console.log(&quot;ERROR!&quot;);
  24. console.log(err);
  25. });

<!-- end snippet -->

NOTE: For anyone without this requirement - please, use other answers to this question or check await setTimeout is not synchronously waiting for additional details/explanations. This kind of overridings are very confusing due to everyone expect common and well-known functions to behavior in a way described in the docs.

答案2

得分: 1

你不能等待setTimeout函数,这是因为你的函数返回undefined。你使用了promise的方式不正确。下面的代码将修复你的问题。

  1. function fetch() {
  2. return new Promise((resolve, reject) => {
  3. setTimeout(() => {
  4. resolve({ name: "User", data: "API Data" });
  5. }, 2000);
  6. });
  7. }
  8. fetch()
  9. .then((val) => {
  10. console.log("完成!");
  11. console.log(val.name);
  12. })
  13. .catch((err) => {
  14. console.log("错误!");
  15. console.log(err);
  16. });

并且请记住不需要更改setTimeout函数。

英文:

You cannot await the setTimeout function, this is because your function returns undefined. You have used the promise in the wrong way. Below code will fix your issue.

  1. function fetch() {
  2. return new Promise((resolve, reject) =&gt; {
  3. setTimeout(() =&gt; {
  4. resolve({ name: &quot;User&quot;, data: &quot;API Data&quot; });
  5. }, 2000);
  6. });
  7. }
  8. fetch()
  9. .then((val) =&gt; {
  10. console.log(&quot;DONE!&quot;);
  11. console.log(val.name);
  12. })
  13. .catch((err) =&gt; {
  14. console.log(&quot;ERROR!&quot;);
  15. console.log(err);
  16. });

And remember that there is no need to change the setTimeout function.

答案3

得分: 0

问题在于 setTimeout 实际上不会返回一个 Promise,这意味着你无法在 setTimeout 中使用 await,这就是为什么 var object; 会立即返回为 undefined 的原因。

要解决这个问题,你只需要将 setTimeout 包装在一个 Promise 中,就像这样:

  1. function setTImeoutAwait(time) {
  2. return new Promise((resolve) => {
  3. setTimeout(resolve, time);
  4. });
  5. }

然后你可以这样使用它:

  1. async function fetch() {
  2. var object;
  3. await setTImeoutAwait(1000).then(() => {
  4. object = { name: "test" };
  5. });
  6. return object;
  7. }
英文:

The problem is that setTimeout does not actually return a promise, which means you cannot use await with setTimeout, that's why the var object; is returned instantly as undefined.

To solve this issue, you simply need to wrap setTimeout around a promise.
Like so:

  1. function setTImeoutAwait(time) {
  2. return new Promise((resolve) =&gt; {
  3. setTimeout(resolve, time);
  4. });
  5. }

You can then use it like this:

  1. async function fetch() {
  2. var object;
  3. await setTImeoutAwait(1000).then(() =&gt; {
  4. object = { name: &quot;test&quot; };
  5. });
  6. return object;
  7. }

huangapple
  • 本文由 发表于 2023年1月8日 23:44:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/75049122.html
匿名

发表评论

匿名网友

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

确定