我在init函数的作用域之外声明了一些函数,并在init中带参数调用它们。我已经设置了一些控制台日志来跟踪进度以及为什么我没有得到期望的结果(即使是错误的),并注意到它完全跳过了函数声明中的控制台日志。此外,我使用 Chrome 的调试器单步执行脚本,发现一旦到达函数声明的头部,它就会跳到 init 中的下一行,而不会单步执行该函数。
我的想法是这与必须使用回调有关,但目前我不确定。
我已经测试了各种顺序、声明函数的各种形式,从在 init 中声明它们到嵌套它们的声明。无论给予还是索取,所有结果都相同。这让我认为编译器认为这需要更多时间并立即跳到下一行。
这是代码的相关部分。
export default class Fundo extends FlexPlugin {
constructor(PLUGIN_NAME) {
super(PLUGIN_NAME);
this.state = {
token: "",
cid: "",
};
this.fetchToken = this.fetchToken.bind(this);
this.fetchCustomer = this.fetchCustomer.bind(this);
}
fetchToken = info => {
const http = require("https");
http.request(info, res => {
var chunks = [];
res.on("data", function(chunk) {
chunks.push(chunk);
});
res.on("end", () => {
var body = Buffer.concat(chunks);
var temp = JSON.parse(body);
this.setState({
token: "Token " + temp.accessToken,
});
console.log(this.token);
});
});
};
fetchCustomer = (info2, password) => {
const http = require("https");
http.request(info2, res => {
var chunks = [];
res.on("data", chunk => {
chunks.push(chunk);
});
res.on("end", () => {
var body = Buffer.concat(chunks);
var temp = JSON.parse(body);
var temp2 = temp.items[0].customerId;
this.setState({
cid: temp2,
});
console.log(this.state.cid);
});
});
};
init(flex, manager) {
const options = {
method: "GET",
hostname: "hostnamegoeshere.com",
headers: {
//api header info
},
};
const options2 = {
method: "GET",
hostname: "api.epicloansystems.com",
headers: {
//moreheaderinfo
},
};
this.fetchToken(options);
this.fetchCustomer(options2, this.state.token);
flex.CRMContainer.defaultProps.uriCallback = cid => {
console.log("hereD");
return `https://hostandpath.aspx?cid=${this.state.cid}`;
};
}
}
最佳答案
在 JavaScript 中,异步代码(例如发出 HTTP 请求)是非阻塞的,这意味着您为异步代码提供的回调将在将来的某个时刻执行。您在 http.request
中提供的回调将异步执行。
所以基本上,当您调用 this.fetchCustomer
时,this.fetchToken
实际上并未使用您需要的 token 设置状态!
你需要类似的东西
// not an exact solution here but this is roughly
// what the setup would look like if fetchToken returned a promise
this.fetchToken(options).then(() => { this.fetchCustomer(this.state.token) });
了解更多信息的好资源:https://blog.bitsrc.io/understanding-asynchronous-javascript-the-event-loop-74cd408419ff
一般来说,您可以在此处使用类似 Promise 的内容。控制相互依赖的异步代码流。
关于javascript - 处理 JavaScript 中的异步行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57260635/