var myPromise = new Promise(async function(resolve, reject){
// idon't want to resolve after 10seconds... i want to resovle it after show_me function get called and finsih it's job.....
setTimeout(resolve, 10000)
});
let xarr = [];
let yarr = [];
async function show_me(){
console.log("called");
let url = 'http://localhost:3000/get_transaction2';
let response = await fetch(url);
let commits = await response.json(); // read response body and parse as JSON
for(let i= 0; i<commits.length; i++){
let lastdate = commits[i].last_date;
let cl = commits[i].collect_location.split(' ');
let battery = commits[i].battery_left;
let broked = commits[i].broken;
collect_point = new jsPoint(cl[0],cl[1]);
var font=new jsFont("arial","bold","10px");
gr.drawText(`${cl}`,new jsPoint(cl[0],cl[1]),font,bluePen.color,90);
// let x = cl[0] -700;
// let y = -(Number(cl[1])) -400;
let x = cl[0];
let y = -(Number(cl[1]))
console.log(x,y);
xarr[i] = x;
yarr[i] = y;
if(battery<77 || Math.pow(x,2)+Math.pow(y,2)>=Math.pow(290,2)){
plotPointsred(collect_point);
}
if(broked == 1){
plotPointsgreen(collect_point);
}
}
var greenPen=new jsPen(new jsColor("yellow"),5);
gr.drawCircle(greenPen,new jsPoint(700,-400),290);
}
var cities = [];
var recordDistance;
var bestEver;
async function setup() {
await myPromise;
s = createCanvas(1000, windowHeight);
s.position(0,0);
s.style('z-index','1');
console.log("did it worked?");
for (var i = 0; i < xarr.length; i++) {
var v = createVector(xarr[i], yarr[i]);
cities[i] = v;
}
var d = calcDistance(cities);
recordDistance = d;
bestEver = cities.slice();
}
这是我要关注的p5.js事情
我希望setup()等到-> show_me()被调用并完成其工作,然后解决诺言(不必答应,如果我可以使setup()成为对我有好处等到show_me被调用并完成),以便setup()可以完成其工作。
如果您不熟悉p5.js,这是我的问题。我设置了一个函数以在10秒后解决诺言,因为在我打开index.html时会立即调用setup()函数。 setTimeout()函数是我知道如何延迟兑现承诺的唯一选择。
我的英语不太好,所以如果您觉得没有意思,请告诉我。 感谢您的阅读,我一直很欣赏stackoverflow谢谢您
答案 0 :(得分:3)
完成show_me
之后,您可以使用await
和resolve
调用show_me
函数,就像注释中建议的@Chris一样。
var myPromise = new Promise(async function(resolve, reject){
await show_me();
resolve();
});
但是,老实说,您为什么要使用Promise来检查是否完成了另一个Promise? 进行以下示例将得到相同的结果。
async function setup() {
await show_me(); // Instead of await myPromise
...