停止并执行承诺Javacript

发布于 2025-01-28 13:28:22 字数 1286 浏览 3 评论 0原文

如何同步执行HTTP请求并使用JavaScript存储结果?

给定以下JavaScript模块:

var Promise = require("promise");                                                                                                                                                                       

function myReq(url) {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.open("GET", url);
    xhr.responseType = 'json';
    xhr.onload = () => {
      if (xhr.status >= 400){
        console.log("got rejected");
        reject({status: xhr.status, statusText: xhr.statusText});
      } else {
        console.log("resolved");
        resolve({data: xhr.response});
      }
    };
    xhr.onerror = () => {
      console.log("Error was called");
      reject({status: xhr.status, statusText: xhr.statusText});
    };
    xhr.send();
  });
}

export default myReq;

我希望该请求中的JSON对象存储在另一个脚本中的本地变量中。但是,当我尝试此代码时,它会运行异步。

1. import myReq from '../../lib/myReq';
2. const urlTest = "localhost://3000:/somepath";
3. const test = myReq(urlTest).then((a) => {console.log(a); return a;}).catch((b) => console.log(b));
4. console.log(test.data);

我希望它在第3行停止,执行代码,将JavaScript对象存储在测试中,然后恢复代码的其余部分。目前测试是一个承诺和测试。数据未定义。

How do I execute a HTTP request synchronously and store the result in a local object with Javascript?

Given the following javascript module:

var Promise = require("promise");                                                                                                                                                                       

function myReq(url) {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.open("GET", url);
    xhr.responseType = 'json';
    xhr.onload = () => {
      if (xhr.status >= 400){
        console.log("got rejected");
        reject({status: xhr.status, statusText: xhr.statusText});
      } else {
        console.log("resolved");
        resolve({data: xhr.response});
      }
    };
    xhr.onerror = () => {
      console.log("Error was called");
      reject({status: xhr.status, statusText: xhr.statusText});
    };
    xhr.send();
  });
}

export default myReq;

I want the json object from this request stored in a local variable in another script. However, when I try this code it runs it async.

1. import myReq from '../../lib/myReq';
2. const urlTest = "localhost://3000:/somepath";
3. const test = myReq(urlTest).then((a) => {console.log(a); return a;}).catch((b) => console.log(b));
4. console.log(test.data);

I want it to stop at line 3, execute the code, store the javascript object in test, and the resume execution of the rest of the code. Right now test is a Promise and test.data is undefined.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

醉殇 2025-02-04 13:28:22

myreq返回承诺,而不仅仅是数据!这就是为什么您需要使用然后& 捕获块,或者使用等待

// myReq function returns a Promise, NOT a value! (Not returning 5!)
function myReq(url) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(5);
    }, 5000);
  });
}

// Option 1
myReq('someurl').then((data) => {
  console.log('data (option 1)', data); // You can use the data here, inside the 'then' block
}).catch((error) => {
  console.log('error', error);
});

// Option 2
const run = async () => {
  try {
    const data = await myReq('someurl'); // await must be called from an 'async' function
    console.log('data (option 2)', data); // You can use the data here, inside the 'try' block
  } catch (error) {
    console.log('error', error);
  }
};
run();

myReq returns a Promise, NOT just the data! That is why you need to use then & catch blocks, or alternatively use await.

// myReq function returns a Promise, NOT a value! (Not returning 5!)
function myReq(url) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(5);
    }, 5000);
  });
}

// Option 1
myReq('someurl').then((data) => {
  console.log('data (option 1)', data); // You can use the data here, inside the 'then' block
}).catch((error) => {
  console.log('error', error);
});

// Option 2
const run = async () => {
  try {
    const data = await myReq('someurl'); // await must be called from an 'async' function
    console.log('data (option 2)', data); // You can use the data here, inside the 'try' block
  } catch (error) {
    console.log('error', error);
  }
};
run();

雨的味道风的声音 2025-02-04 13:28:22

如果要将其转换为同步过程,则可以直接使用async/等待来处理该过程,而不是直接移动到下一步。就像您可以做类似的事情一样:

try {
const result = await myReq(url);
} catch (e) {
 // Handle error generated in the process
}

记住您只能async/egait in Pair表示,只有在async函数中,您才能使用等待 keyword。有关更多详细信息,您可以访问此

希望这会有所帮助。祝你有美好的一天。

If you want to convert this to a synchronous process you can directly use the async/await to handle the process rather than directly moving to next step. Like you can do something like:

try {
const result = await myReq(url);
} catch (e) {
 // Handle error generated in the process
}

remember you can only async/await in pair means that only inside an async function you can use await keyword. For more details you can visit this article

Hope this helps. Have a good day.

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