我具有以下功能
const getQuotes = symbol => {
let quotes = {};
new DeltaRestClient(api_key, api_secret).then(client => {
const linkOptions = createIdentifiers(symbol, false);
Object.entries(linkOptions).forEach(entry => {
client.apis.Products.getTicker({ symbol: entry[1] }).then(response => {
const ticker = JSON.parse(response.data.toString());
quotes[entry[0]] = parseFloat(ticker.result.close);
});
});
});
return quotes;
};
我叫
const start = async () => {
const quotes = await getQuotes("ABCD");
console.log(quotes);
};
但是由于异步性,getQuotes在解析所有.then并返回空对象之前返回。
如何更改此值,以便仅在所有.then都解析后才返回值?
答案 0 :(得分:1)
您还必须等待正在调用的函数:
const getQuotes = async symbol => {
let quotes = {};
const client = await new DeltaRestClient(api_key, api_secret);
const linkOptions = createIdentifiers(symbol, false);
for (const entry of Object.entries(linkOptions)) {
const response = await client.apis.Products.getTicker({ symbol: entry[1] });
const ticker = JSON.parse(response.data.toString());
quotes[entry[0]] = parseFloat(ticker.result.close);
}
return quotes;
};
并相应地调用它:
const start = async () => {
const quotes = await getQuotes("ABCD");
console.log(quotes);
};
通常将async / await和Promise混合使用。然后/.catch导致容易被误解的可疑代码。
如果愿意,可以通过分解entry元素来提高可读性:
for (const [key, symbol] of Object.entries(linkOptions)) {
const response = await client.apis.Products.getTicker({ symbol, });
const ticker = JSON.parse(response.data.toString());
quotes[key] = parseFloat(ticker.result.close);
}