停止并执行承诺Javacript
如何同步执行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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
myreq
返回承诺,而不仅仅是数据!这就是为什么您需要使用然后
&捕获
块,或者使用等待
。myReq
returns a Promise, NOT just the data! That is why you need to usethen
&catch
blocks, or alternatively useawait
.如果要将其转换为同步过程,则可以直接使用
async/等待
来处理该过程,而不是直接移动到下一步。就像您可以做类似的事情一样:记住您只能
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:remember you can only
async/await
in pair means that only inside anasync
function you can useawait
keyword. For more details you can visit this articleHope this helps. Have a good day.