正如标题所说,我可以放置以下异步函数:
callArgos("fifa 17", function(title, price) {
console.log("Argos title " + title + " price " + price);
})
在另一个函数中说:
function foo() {
callArgos("fifa 17", function(title, price) {
console.log("Argos title " + title + " price " + price);
})
}
然后调用函数foo,返回标题和价格,并将它们分配给全局变量?
我有三个独立的异步函数从三个不同的网站获取价格,并使用回调函数返回价格。我希望然后将返回的值分配给全局变量,以便比较所有三个价格。我不确定它是否可以在JS和Node.js中使用。
你们觉得怎么样?
答案 0 :(得分:-2)
不确定。看看这个小提琴。这对你有用吗?
https://jsfiddle.net/9djnexrv/
// Prices will be stored here
var prices = [];
// Dummy-function to mock async behaviour
function callArgos(someString, someCallback) {
setTimeout(function() {
someCallback(someString, 42);
}, Math.random()*100);
}
// Actual function
function foo() {
callArgos("fifa 15", function(title, price) {
prices[0] = price;
console.log("Argos title " + title + " price " + price, prices);
});
callArgos("fifa 16", function(title, price) {
prices[1] = price;
console.log("Argos title " + title + " price " + price, prices);
});
callArgos("fifa 17", function(title, price) {
prices[2] = price;
console.log("Argos title " + title + " price " + price, prices);
});
}
// Execute function
foo();